English 中文(简体)
在一项活动中动态登记广播接收器并解除该接收器的登记和登记,同时允许该接收器在活动之外运行
原标题:Dynamically registering and unregistering a broadcast receiver in an activity while allowing it to run outside the activity as well

我试图注册一个广播接收器, 这样当屏幕打开时, 飞机模式也打开了。 只要我留在我注册的活动中, 它就起作用了, 但是一旦我离开活动, 它就停止工作。 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 () 上写些什么有关?... 虽然我以为它注册后会一直工作到未登记为止,

最佳回答

我不确定您的广播接收器在活动停止后是否会工作,因为您的接收器是按程序而不是静态地通过显示器注册的(因为机器人不允许你这样做)。

我看过你的代码 试图理解代码是做什么的 但从几条线来看 这并不简单...

但无论如何, 您为什么不在屏幕状态下创建您注册听众的服务? 这样即使活动停止了, 服务也不会停止执行 。

每次服务通知屏幕打开/关闭时,您都可以向您的主要活动发送信息(请查