我试图注册一个广播接收器, 这样当屏幕打开时, 飞机模式也打开了。 只要我留在我注册的活动中, 它就起作用了, 但是一旦我离开活动, 它就停止工作。 Android 宣言是静态的, 所以我不能使用它。 此外, Android 宣言方法不允许你使用 SCREEN ON, 因为当屏幕醒来时, Android不希望你运行一堆事情, 所以它必须使用 Receiver 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()?
错误是否与不告诉广播接收器在Pause () 或Destroy () 上写些什么有关?... 虽然我以为它注册后会一直工作到未登记为止,