我正在尝试注册一个广播接收器,这样当屏幕打开时,飞行模式也会打开。只要我停留在注册它的活动中,它就会工作,但一旦我离开活动,它就会停止工作。安卓Manifest是静态的,所以我不能使用它,此外,安卓Manifest方法不允许你使用SCREEN_ON,因为安卓不希望你在屏幕唤醒时运行一堆东西,所以它必须使用registerReceiver AFAIK来完成。
我的活动:
public class WakeActivity extends Activity {
IntentFilter screenon = new IntentFilter("android.intent.action.SCREEN_ON");
//Skipped a bunch of code here to keep it relevant. Remember, the broadcast receiver
//does in fact work while I'm in the activity, so the problem isn't with
//the missing code here. Still, let me know if I'm missing something.
//The following method is called within onCreate()
protected void airplane(int i) {
Screen_On screenon_airplane = new Screen_On();
if (i == 0) {
screenon_airplane.airplanei = 0;
registerReceiver(screenon_airplane, screenon);
} else if (i == 1) {
screenon_airplane.airplanei = 1;
registerReceiver(screenon_airplane, screenon);
} else if (i == -1) {
unregisterReceiver(screenon_airplane);
}
}
}我的广播接收器:
public class Screen_On extends BroadcastReceiver {
public int airplanei;
@Override
public void onReceive(final Context context, Intent intent) {
boolean isEnabled = Settings.System.getInt(
context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
0) == 1;
if (airplanei == 0) {
if (isEnabled != false) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0);
Intent turnplaneoff = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
turnplaneoff.putExtra("state", 0);
context.sendBroadcast(turnplaneoff);
}
} else if (airplanei == 1) {
if (isEnabled == false) {
Settings.System.putInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 1);
Intent turnplaneon = new Intent(
Intent.ACTION_AIRPLANE_MODE_CHANGED);
turnplaneon.putExtra("state", 1);
context.sendBroadcast(turnplaneon);
}
}
}
}LogCat错误:-
05-17 23:44:24.886: E/ActivityThread(2435): Activity com.dragonheart.autodroid.ActionActivities.WakeActivity has leaked IntentReceiver com.dragonheart.autodroid.BroadCastRecievers.Screen_On@414271b0 that was originally registered here. Are you missing a call to unregisterReceiver()?这个错误会不会与没有告诉广播接收器在onPause()或onDestroy()?...Although中做什么有关?我认为一旦注册了,它就会一直工作到取消注册,而不管活动是什么……
发布于 2012-05-24 18:48:34
我不确定一旦activity停止,你的广播接收器是否会工作,因为你的接收器是以编程方式注册的,而不是通过清单静态注册的(因为android不允许你这样做)。
我看过你的代码,试图理解代码的作用,但仅仅几行代码并不简单……
但不管怎样,为什么不创建一个服务,在其中将侦听器注册到屏幕状态?这样,即使在活动停止之后,服务也不会停止执行。
每当服务注意到屏幕打开/关闭时,你就可以向你的主要活动发送一条消息(检查documentation)。
请参阅前面的问题,以及如何使用LocalBroadcastReceiver的示例:LINK
https://stackoverflow.com/questions/10734538
复制相似问题