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

当前回答

我认为你们的货单需要加上:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

其他回答

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

请注意,在问题的开头,有一个拼写错误:

<行动android: name = " android.intent.action._BOOT_COMPLETED " / >

而不是:

<行动android: name = " android.intent.action.BOOT_COMPLETED " / >

一个小“_”和所有这些麻烦:)

我认为你们的货单需要加上:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

我有一个额外的<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.intent.action.BOOT_COMPLETED"权限和intent-filter,你实际上没有做错什么。

注意,如果你在Android 4。X,你必须在启动服务之前运行广播监听器,这意味着,你必须先添加一个活动,一旦你的广播接收器运行,你的应用程序应该像你预期的那样运行,然而,在Android 4上。X,我还没有找到一种方法来启动启动没有任何活动的服务,我认为谷歌这样做是出于安全原因。