我一直试图在设备在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" />

BroadcastReceiver

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");
    }
}

当前回答

我有一个额外的<category>-tag,不知道这是否有任何区别。

<receiver android:name="BootIntentReceiver">  
        <intent-filter>  
            <action android:name="android.intent.action.BOOT_COMPLETED" />  
            <category android:name="android.intent.category.HOME" />  
        </intent-filter>  
</receiver>

你有没有试过省略if子句"android.intent.action.BOOT_COMPLETED".equals(intent. getaction(),因为接收器可能只接收该意图?

其他回答

在挂载外部存储之前,BOOT_COMPLETE被发送执行。如果你的应用被安装到外部存储,它不会收到BOOT_COMPLETE广播消息。为了防止这种情况,可以将应用程序安装在内部存储中。只需在menifest.xml中添加这一行即可

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:installLocation="internalOnly"
... >

一些HTC设备可以启用“快速启动”功能,这更像是深度休眠,而不是真正的重新启动,因此不应该给出BOOT_COMPLETE意图。为了恢复这个,你可以在你的接收器中添加这个intent过滤器:

            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            </intent-filter>

其他答案看起来不错,但我认为我应该把所有问题都归结为一个完整的答案。

你需要在AndroidManifest.xml文件中添加以下内容:

In your <manifest> element: <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> In your <application> element (be sure to use a fully-qualified [or relative] class name for your BroadcastReceiver): <receiver android:name="com.example.MyBroadcastReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> (you don't need the android:enabled, exported, etc., attributes: the Android defaults are correct) In 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>中有一个拼写错误

如果在接收类中保留空构造函数,就会遇到这个问题。删除空构造函数后,onRreceive方法开始正常工作。

参考此链接http://khurramitdeveloper.blogspot.in/2013/06/start-activity-or-service-on-boot.html 在服务上使用引导的步骤

作为附加信息:BOOT_COMPLETE在外部存储挂载之前发送给应用程序。因此,如果应用程序被安装到外部存储,它将不会收到BOOT_COMPLETE广播消息。

更多详细信息,请参见广播接收器侦听“引导完成”部分。