Android 活动中的广播接收器

Android 活动中的广播接收器,android,broadcastreceiver,Android,Broadcastreceiver,我想更改活动的KeepScreenOn值,因此我想在活动中使用BroadcastReceiver。我在onCreate中向以下人员注册接收器: registerReceiver(receiver, new IntentFilter("ACTION_POWER_CONNECTED")); registerReceiver(receiver, new IntentFilter("ACTION_POWER_DISCONNECTED")); 并在onPause中注销它: unr

我想更改活动的KeepScreenOn值,因此我想在活动中使用BroadcastReceiver。我在onCreate中向以下人员注册接收器:

registerReceiver(receiver, new IntentFilter("ACTION_POWER_CONNECTED"));
            registerReceiver(receiver, new IntentFilter("ACTION_POWER_DISCONNECTED"));
并在onPause中注销它:

unregisterReceiver(receiver);
接收器如下所示:

    private BroadcastReceiver receiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
            findViewById(R.id.fullscreen_content).setKeepScreenOn(true);
        } else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
            media=MediaPlayer.create(context,R.raw.battery);
            media.start();
            findViewById(R.id.fullscreen_content).setKeepScreenOn(false);
        }
    }
};

没有错误,在断开/连接电源时,它不会改变任何东西。有什么建议吗?

让您的
接收者在
AndroidManifest.xml
中注册操作

    <receiver android:name="com.app.example.firstapp.MyReceiver">
            <intent-filter>
                <action android:name="android.intent.action.SCREEN_OFF"></action>
                <action android:name="android.intent.action.SCREEN_ON"></action>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED"></action>
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"></action>
                 <action android:name="android.intent.action.ACTION_SHUTDOWN"></action>
            </intent-filter>
        </receiver>

也不要忘记添加权限

<uses-permission android:name="android.permission.BATTERY_STATS"/>

您应该使用定义的常量,而不是字符串值:

IntentFilter(Intent.ACTION_POWER_CONNECTED)
而不是:

IntentFilter("ACTION_POWER_CONNECTED")

首先在接收机中设置调试点,看看它是否真的在发射

如果不是,则:

我现在没有坐在我的IDE上,但我认为这不会起作用,因为你用不同的过滤器注册同一个接收器,第二个会覆盖第一个动作

如果希望一个接收器具有多个操作,则应创建一个筛选器,并使用IntentFilter
addAction()
方法向其添加多个操作。然后,当调用接收方时,应该使用Intent
getAction()
方法来确定触发了哪个操作

您也应该只在
onStart
onResume
中注册您的接收器

如果它正在发射:


要保持屏幕处于打开状态,请尝试以下解决方案:

“但它根本不工作”,然后发生了什么?任何错误/异常?没有错误,在断开/连接电源时,它不会改变任何东西。您是否尝试过调试以检查它是否正在执行接收器块?如果未添加,也要添加清单权限是吗?即使它不是独立类,我也必须在清单中注册它吗?它在我的活动中。请尝试通过receiver中的意图过滤器注册所有上述操作。