我想更改 Activity 的 KeepScreenOn 值,因此我想在 Activity 中使用 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);
}
}
};
没有错误,在断开/连接电源时它不会改变任何东西。有什么建议吗?
最佳答案
您应该使用定义的常量,而不是字符串值:
IntentFilter(Intent.ACTION_POWER_CONNECTED)
代替:
IntentFilter("ACTION_POWER_CONNECTED")
关于android - Activity 中的 BroadcastReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26651120/