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

当前回答

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

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

其他回答

我刚刚发现,可能是因为设置>电源中的快速启动选项

当我关闭这个选项时,我的应用程序接收到一个this广播,而不是其他。

顺便说一下,我在HTC Incredible S上安装了Android 2.3.3。

希望能有所帮助。

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

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

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

我有一个额外的<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(),因为接收器可能只接收该意图?

在尝试了所有提到的答案和技巧后,我终于找到了为什么代码不能在我的手机上工作。一些Android手机,如“华为荣耀3C Android 4.2.2”,在他们的设置中有一个状态管理器菜单,你的应用程序必须在列表中勾选。 :)