【发布时间】:2015-02-08 19:42:49
【问题描述】:
背景和问题
我在stackoverflow上查看了几十个教程、示例和问题,这些都与手机关机后服务未注册的问题有关。
我的问题几乎相似,但略有不同:我使用IntentService(我需要从外部数据库收集数据并将其显示为通知)并且服务每 30 秒运行一次,直到我切换手机关机。
有趣的部分
奇怪的行为来了!我把手机转回来,IntentService 只注册了一次。启动后,我只收到一次通知(在示例中,为了简单起见,我只使用日志),然后再也不会收到通知。
部分 Activity 代码(我可以在其中设置服务)
private void setRecurringAlarm(Context context) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, BackgroundDataServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(), 30*1000, pending);
}
IntentService
public class BackgroundDataService extends IntentService {
....
@Override
protected void onHandleIntent(Intent intent) {
Log.i("BACKGROUNDDATASERVICE STATUS", "running");
}
}
广播接收器
public class BackgroundDataServiceReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent dailyUpdater = new Intent(context, BackgroundDataService.class);
context.startService(dailyUpdater);
}
}
清单
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
...
<service android:name="com.example.blgui3.BackgroundDataService" >
</service>
<receiver android:name="com.example.blgui3.BackgroundDataServiceReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
...
</application>
据我所知,我的 service 是否需要执行后台任务,例如使用AsyncTask从外部数据库获取数据,那么推荐使用IntentService。即使我在启动后启动应用程序,该服务仍然只运行一次,因此它根本没有注册 BOOT_COMPLETE 操作。在为此挣扎了几个小时之后,我完全不知道我哪里出错了。
【问题讨论】:
标签: android broadcastreceiver intentservice android-intentservice