Percy

尝试在Android上启动时启动服务

java

当设备在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");
    }
}

阅读 361

收藏
2020-12-07

共2个答案

小编典典

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

2020-12-07
小编典典

其他答案看起来不错,但我想我会将所有内容都包装成一个完整答案。

您的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>
2020-12-07