当设备在 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");
}
}
其他答案看起来不错,但我想我会将所有内容都打包成一个完整的答案。
您的 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/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) | Powered by Discuz! X3.4 |