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我知道该服务正在连续运行,因为我正在密切注意该过程,发现它运行正常并且没有以任何方式重新启动,并且因为我看到在启动警报之前它已打开的连接不会被中断。
正如JesusFreke所建议的那样,问题在于peekService()
只能返回现有 IBinder
对象。由于该服务已由系统重新启动,并且此时还没有Activity
绑定到该服务的IBinder
对象,因此该对象尚不存在。因此null
返回a。可惜的是,文档完全错过了这个事实。
由于我绝对不想在未运行的情况下启动该服务startService()
,因此使用它似乎是一个坏主意,因此我求助于该服务的静态属性(无论如何都存在)。
归档时间: |
|
查看次数: |
765 次 |
最近记录: |