gpt4 book ai didi

java - 广播接收器不能静态工作

转载 作者:行者123 更新时间:2023-12-02 00:33:29 24 4
gpt4 key购买 nike

我想通过广播接收器在手机电源连接和断开时发出通知。但问题是,当我在 list 中定义接收器时,它不起作用,但如果我动态定义它,它就可以很好地工作。这是我的 list .xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.batterymanager">


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".PowerConnectionReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
</intent-filter>
</receiver>
</application>

</manifest>

这是我的广播:

package com.example.batterymanager;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class PowerConnectionReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
/*if (intent.getAction().equals("android.intent.action.ACTION_POWER_CONNECTED")) {
Toast.makeText(context, "Power Connected", Toast.LENGTH_SHORT).show();
} else if (intent.getAction().equals("android.intent.action.ACTION_POWER_DISCONNECTED")){
Toast.makeText(context, "Power Disconnected", Toast.LENGTH_SHORT).show();
}*/

Toast.makeText(context, "" + intent.getAction(), Toast.LENGTH_SHORT).show();
Log.i("HUU", intent.getAction());
}
}

我不知道为什么它不起作用! ):

最佳答案

新的 Android 限制:

As part of the Android 8.0 (API level 26) Background Execution Limits, apps that target the API level 26 or higher can no longer register broadcast receivers for implicit broadcasts in their manifest. However, several broadcasts are currently exempted from these limitations. Apps can continue to register listeners for the following broadcasts, no matter what API level the apps target.

https://developer.android.com/guide/components/broadcast-exceptions

关于java - 广播接收器不能静态工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57995548/

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