gpt4 book ai didi

java - Android BroadcastReceiver 未收到 BOOT_COMPLETED 事件

转载 作者:行者123 更新时间:2023-12-02 13:17:30 24 4
gpt4 key购买 nike

我在我的应用程序中创建了一个 BroadcastReceiver 来接收BOOT_COMPLETED 事件 (BootReceiver),然后启动一个服务 (NtService),该服务有一个公共(public)静态 boolean 值 (started),通过以下方式设置为 true他的 onCreate() 方法,但是当我将 var 打印到 MainActivity 中的控制台时, boolean 值仍然为 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>

最佳答案

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

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

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

关于java - Android BroadcastReceiver 未收到 BOOT_COMPLETED 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43710056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com