我正在尝试注册一个广播接收器,以便当屏幕打开时,飞行模式也会打开。只要我留在我注册的活动中,它就可以工作,但是一旦我离开活动,它就会停止工作。Android Manifest 是静态的,所以我不能使用它,此外,Android Manifest 方法不允许您使用 SCREEN_ON 因为 Android 不希望您在屏幕唤醒时运行一堆东西,所以它必须由使用 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() 中的内容有关?...虽然我认为一旦注册它,它会一直工作到未注册,无论活动如何...