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

时间:2014-12-10 01:18:01

标签: android android-service

我正在使用

开始服务
startService(new Intent(this, RelayService.class));

然后服务使用

启动警报
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);

然后BroadcastReceiver SyncAlarmReciver正在尝试使用

获取服务
RelayServiceBinder relay = (RelayServiceBinder) 
    peekService(context, new Intent(context, RelayService.class));

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

如果有帮助,以下是指向上述三段代码的链接:main activityservicebroadcast receiver

P.S。我知道服务正在连续运行因为我正在密切关注这个过程并看到它正常运行并且没有以任何方式重新启动,而且因为我看到它在启动警报之前打开了连接不会被打断。

1 个答案:

答案 0 :(得分:4)

正如JesusFreke所建议的,问题是peekService()只能返回现有的 IBinder对象。当系统重新启动服务并且此时没有绑定到服务的Activity时,IBinder对象尚不存在。因此返回null。令人遗憾的是,文档完全忽略了这一事实。

因为我肯定不想在没有运行的情况下启动服务,所以使用startService()似乎是一个坏主意,所以我求助于查询服务的静态属性(无论如何都在那里)。