0

我正在尝试注册一个广播接收器,以便当屏幕打开时,飞行模式也会打开。只要我留在我注册的活动中,它就可以工作,但是一旦我离开活动,它就会停止工作。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() 中的内容有关?...虽然我认为一旦注册它,它会一直工作到未注册,无论活动如何...

4

1 回答 1

0

我不确定您的广播接收器是否会在活动停止后工作,因为您的接收器已经以编程方式注册,而不是通过清单静态注册(因为 android 不允许您这样做)。

我查看了您的代码,试图了解代码的作用,但这并不简单,仅几行...

但无论如何,你为什么不创建一个服务来将监听器注册到屏幕状态呢?这样,即使活动停止后,服务也不会停止执行。

每次服务通知屏幕打开/关闭时,您都可以向您的主要活动发送消息(检查文档)。

请参阅上一个问题,以及如何使用 LocalBroadcastReceiver 的示例:LINK

于 2012-05-24T10:48:33.647 回答