我正在编码的应用程序有问题。
每次广播时,我都需要接收 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,然后重新启动它。杀死和重生之间的时间通常在 5 秒左右,但有时这足以错过一些意图,从而给我的应用程序的用户带来问题。这些意图只能通过 registerReceiver 注册,所以我无法在清单中注册它们。我怎么能听那些意图而不被杀死或错过一些?
谢谢!