我希望更改活动的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);
}
}
};没有错误,当断开/连接电源时,它不会改变任何东西。有什么建议吗?
发布于 2014-10-30 11:09:21
您应该使用定义的常量,而不是字符串值:
IntentFilter(Intent.ACTION_POWER_CONNECTED)而不是:
IntentFilter("ACTION_POWER_CONNECTED")发布于 2014-10-30 11:02:54
是否在Receiver中注册了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"/>发布于 2014-10-30 11:15:09
首先,在接收器中设置调试点,以查看它是否真正启动。
如果不是这样的话:
我现在没有坐在我的IDE上,但我认为这是行不通的,因为您用不同的过滤器注册相同的接收器,第二个将覆盖第一个操作。
如果希望一个接收方具有多个操作,则应该创建一个筛选器,并使用IntentFilter addAction()方法向其添加多个操作。然后,当您的接收方被调用时,您应该使用意图getAction()方法来确定哪个操作已经触发。
您还应该只在onStart或onResume中注册您的接收器。
如果它在开火:
要保持屏幕正常运行,请在这里尝试解决方案:Keep Screen On Flag
https://stackoverflow.com/questions/26651120
复制相似问题