即使服务正在运行,peekService()也将返回null,即使在OOM终止后由系统重新启动了服务

squ*_*rel 4 android android-service

我正在使用开始服务

startService(new Intent(this, RelayService.class));
Run Code Online (Sandbox Code Playgroud)

然后该服务使用发出警报

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, SyncAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent,
    PendingIntent.FLAG_CANCEL_CURRENT);
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 
    SystemClock.elapsedRealtime() + SYNC_EVERY_MS, SYNC_EVERY_MS, pi);
Run Code Online (Sandbox Code Playgroud)

然后BroadcastReceiver SyncAlarmReciver尝试使用获取服务

RelayServiceBinder relay = (RelayServiceBinder) 
    peekService(context, new Intent(context, RelayService.class));
Run Code Online (Sandbox Code Playgroud)

在其他应用程序需要更多内存时,在应用程序被终止后,系统重新启动该服务之前,一切正常。重新启动后,该服务使用相同的代码重新启动警报,但peekService()返回null。通过调试消息,我看到context服务和广播接收器中的内容以及RelayService对象是相同的,即这些对象是内存中的相同对象。我怎么解决这个问题?

如果有帮助,这里是指向上述三段代码的链接:主要活动服务广播接收器

PS我知道该服务正在连续运行,因为我正在密切注意该过程,发现它运行正常并且没有以任何方式重新启动,并且因为我看到在启动警报之前它已打开的连接不会被中断。

squ*_*rel 5

正如JesusFreke所建议的那样,问题在于peekService()只能返回现有 IBinder对象。由于该服务已由系统重新启动,并且此时还没有Activity绑定到该服务的IBinder对象,因此该对象尚不存在。因此null返回a。可惜的是,文档完全错过了这个事实。

由于我绝对不想在未运行的情况下启动该服务startService(),因此使用它似乎是一个坏主意,因此我求助于该服务的静态属性(无论如何都存在)。