当设备在 android 上启动时,我一直在尝试启动服务,但我无法让它工作。我在网上查看了许多链接,但没有一个代码有效。我是不是忘记了什么?
AndroidManifest.xml
<receiver
android:name=".StartServiceAtBootReceiver"
android:enabled="true"
android:exported="false"
android:label="StartServiceAtBootReceiver" >
<intent-filter>
<action android:name="android.intent.action._BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name="com.test.RunService"
android:enabled="true" />
广播接收器
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent serviceLauncher = new Intent(context, RunService.class);
context.startService(serviceLauncher);
Log.v("TEST", "Service loaded at start");
}
}
Best Answer-推荐答案 strong>
其他答案看起来不错,但我想我会将所有内容都打包成一个完整的答案。
您的 AndroidManifest.xml 中需要以下内容文件:
在您的 <manifest> 元素:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
在您的 <application> 元素(确保为您的 BroadcastReceiver 使用完全限定的 [或相对] 类名):
<receiver android:name="com.example.MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
(你不需要 android:enabled , exported 等,属性:Android默认是正确的)
在 MyBroadcastReceiver.java :
package com.example;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, MyService.class);
context.startService(startServiceIntent);
}
}
从原来的问题: 尚不清楚 <receiver> 元素位于 <application> 元素 不清楚 BroadcastReceiver 的完全限定(或相对)类名是否正确。已指定 <intent-filter> 中有错字
关于android - 尝试在 Android 上启动服务,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/2784441/
|