永恒的BroadcastReceiver

时间:2012-06-10 11:53:58

标签: android

我的编码应用程序存在问题 每次广播时我都需要收到ACTION_SCREEN_ON,ACTION_SCREEN_OFF和ACTION_USER_PRESENT意图,因此我的应用程序当然会保留在后台。目前我的应用程序是由设置活动和服务制作的。 ScreenReceiver是一个获取ACTION_SCREEN_ *意图的BroadcastReceiver,而UnlockReceiver获取ACTION_USER_PRESENT意图。该服务注册和取消注册接收者:

public class MainService extends Service {
    ScreenReceiver screenReceiver = null;
    UnlockReceiver unlockReceiver = null;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        doStart();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        doStart();

        return START_STICKY;
    }

    public void doStart() {
        if(screenReceiver != null && unlockReceiver != null)
            return;

        IntentFilter filter;

        if(screenReceiver == null) {
            filter = new IntentFilter();
            filter.addAction(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);

            screenReceiver = new ScreenReceiver();
            registerReceiver(screenReceiver, filter);
        }

        if(unlockReceiver == null) {
            filter = new IntentFilter();
            filter.addAction(Intent.ACTION_USER_PRESENT);

            unlockReceiver = new UnlockReceiver();
            registerReceiver(unlockReceiver, filter);
        }
    }

    @Override
    public void onDestroy() {
        if(screenReceiver != null)
            unregisterReceiver(screenReceiver);

        if(unlockReceiver != null)
            unregisterReceiver(unlockReceiver);
    }
}  

但有时Android会杀死我的服务以释放一些RAM,然后重启它。 kill和respawn之间的时间通常是5秒左右,但有时这可能会错过一些意图导致我的应用程序的用户出现问题。那些意图只能注册到registerReceiver,所以我不能在清单中注册它们。我怎么能听到这些意图而不会被杀或遗失?

谢谢!

1 个答案:

答案 0 :(得分:0)

  

我怎么能听到这些意图而不会被杀死或遗失?

你不是。您重写您的应用程序要么不使用这些广播,要么在丢失广播的情况下更具弹性。毕竟,它不只是" Android终止了我的服务以释放一些RAM,然后重新启动它,但是任务经理等可以摆脱你的服务。