Android BroadcastReceiver 未收到 BOOT_COMPLETED 事件

Android BroadcastReceiver not receiving BOOT_COMPLETED event

我在我的应用程序中创建了一个 BroadcastReceiver 来接收 BOOT_COMPLETED 事件 (BootReceiver) 然后启动一个服务 (NtService) 这个服务有一个 public 静态布尔值 (started) 被他设置为 true onCreate() 方法,但是当我在 MainActivity 中将 var 打印到控制台时,布尔值仍然为 false。

该应用程序安装在 内部存储 中,我通过在 adb shell 上提交此命令在 android studio 模拟器中对其进行调试:

am broadcast -a android.intent.action.BOOT_COMPLETED

代码如下:

BootReceiver

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class BootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Intent i = new Intent(context, NtService.class);
            context.startActivity(i);
    }
}

NtService

   import android.app.Service;
   import android.content.Intent;
   import android.os.IBinder;

   public class NtService extends Service {
     public static boolean started;

     public NtService() {
     }

     @Override
     public IBinder onBind(Intent intent) {
         return null;
     }

     public void onCreate(){
         started=true;
     }
   }

AndroidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.primerdime.cloudchat">
    <!-- PERMISSION -->
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <application
        android:allowBackup="false"
        android:icon="@drawable/icon"
        android:installLocation="internalOnly"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
            <activity
                android:name=".MainActivity"
                android:windowSoftInputMode="adjustResize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".registration" />
            <!-- SERVICE AND RECEIVER -->
            <service
                android:name=".NtService"
                android:enabled="true"
                android:exported="false" />

            <receiver
                android:name=".BootReceiver"
                android:enabled="true"
                android:exported="false">
                <intent-filter>
                    <action android:name="android.intent.action._BOOT_COMPLETED" />
                </intent-filter>
            </receiver>

    </application>
</manifest>

<receiver> 元素中删除 android:exported="false"。目前,它无法接收来自应用程序外部的广播。

此外,您在 <action> 元素中有错字。应该是 <action android:name="android.intent.action.BOOT_COMPLETED" />.

最后,将 context.startActivity(i); 替换为 context.startService(i);,因为您正在尝试启动服务,而不是 activity。