Everlasting BroadcastReceiver
<p>I've a problem with an app I'm coding.<br>
I need to receive ACTION_SCREEN_ON, ACTION_SCREEN_OFF and ACTION_USER_PRESENT intents everytime they're broadcasted, so my app of course stays in background. At the moment my app is made by a settings activity and a service. ScreenReceiver is a BroadcastReceiver that gets the ACTION_SCREEN_* intents, while UnlockReceiver gets the ACTION_USER_PRESENT intent. The service registers and unregisters the receivers:</p>

<pre><code>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 &amp;&amp; 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);
    }
}  
</code></pre>

<p>But sometimes Android kills my service to free some RAM and then restarts it. The time between the kill and the respawn is usually around 5 seconds, but sometimes this can be enought to miss some intents causing problems to the users of my app. Those intents can be registered only trought registerReceiver, so I can't register them in the manifest. How could I listen to those intents without being killed or missing some?</p>

<p>Thanks!</p>
