【问题标题】:Startup receiver doesn't work on Android 10启动接收器在 Android 10 上不起作用
【发布时间】:2021-07-02 19:10:23
【问题描述】:

我的启动接收器无法在 Android 10 上运行。为什么?

解决方案奖励 50 分。

AndroidManifest.xml

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" tools:ignore="ProtectedPermissions"/>
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>


    <receiver android:name="ServiceStarter"
        android:enabled="true"
        android:exported="true"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter>
            <category android:name="android.intent.category.DEFAULT" />
            <acenter code heretion android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.ACTION_BOOT_COMPLETED" />
            <action android:name="android.intent.action.REBOOT" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="com.htc.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.ACTION_SHUTDOWN" />
        </intent-filter>
    </receiver>

ServiceStarter.Java

public class ServiceStarter extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    SharedPreferences mSharedPref = context.getSharedPreferences("general", MODE_PRIVATE);
    mSharedPref.edit().putInt("Boot", 1).apply();
}
}

MainActivity.java

int boot = mSharedPref.getInt("Boot", 0);
Toast.makeText(this, "Boot: " + String.valueOf(boot), Toast.LENGTH_LONG).show();

当我打开我的应用程序时,“启动”始终为 0。不会调用 onReceive()。

【问题讨论】:

  • 试试这个答案:stackoverflow.com/questions/11325920/… 你可以通过 adb 发送一个 onBootCompleted 信号并测试是否收到了信号。
  • 为什么要把它放在getSharedPreferences中?你可以启动 MainActivity.java
  • @hungcuiga1 我使用共享首选项来存储一个值,以便稍后检查它是否调用了 onReceive。我不想启动 MainActivity。我使用接收器启动后台服务。

标签: android startup


【解决方案1】:

我终于找到了解决方案。从 Android 24 开始,您需要向接收器添加 directBootAware 属性以接收 BOOT_COMPLETED Intent,以防手机被 PIN、图案等锁定。

android:directBootAware="true"

而 onReceive 将是

@Override
public void onReceive(Context context, Intent intent) {
    //Toast.makeText(context, "onReceive Boot", Toast.LENGTH_LONG).show();

    SharedPreferences mSharedPref = context.getSharedPreferences("general", MODE_PRIVATE);


    if(intent != null && intent.getAction() != null){
        if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction()) || 
          Intent.ACTION_LOCKED_BOOT_COMPLETED.equals(intent.getAction())) {
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-12
    • 2011-11-24
    相关资源
    最近更新 更多