最近我将项目升级到了26 Api级别。升级后,我的闹钟管理器不能正常工作了。我不知道问题出在哪里,但我猜测闹钟根本没有起作用,无论是在后台还是针对所有设备(> = M)。我查看了其他的问题并遵循了一些建议,例如“WakefulBroadcastReceiver”。
下面是我的代码和流程:
情景
- 每15分钟设置一个重复的闹钟。
- 调用“WakefulBroadcastReceiver”的操作。
下面是我的代码和流程:
情景
- 每15分钟设置一个重复的闹钟。
Intent dil = new Intent(getApplicationContext(), LocationSyncTaskReceiver.class);
PendingIntent dlpi = PendingIntent.getBroadcast(getApplicationContext(), 225566, dil, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
lFreq = 15;
if(Build.VERSION.SDK_INT>23)
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,(System.currentTimeMillis()+5 * 60 * 1000L),dlpi);
else
am.setRepeating(AlarmManager.RTC_WAKEUP, 5 * 60 * 1000L, lFreq * 60 * 1000L, dlpi);
- 调用“WakefulBroadcastReceiver”的操作。
public class LocationSyncTaskReceiver extends WakefulBroadcastReceiver {
private static final String TAG = LocationSyncTaskReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
WakefulIntentService.acquireStaticLock(context);
Intent locationSync = new Intent(context, SyncLocationTracker.class);
startWakefulService(context,locationSync);
}
以上代码调用了“WakefulIntentService-SyncLocationTracker”。
@Override
public void doWakefulWork(Intent intent) {
userService = UserServiceImpl.getInstance();
Log.d(TAG, "Data Tracker : doWakefulWork called");
if (userService.getLoggedInUser() != null) {
Log.d(TAG, "User is logged in so continuing sync ....");
WakefulIntentService.acquireStaticLock(getApplicationContext());
syncService = DataSyncServiceImpl.getInstance();
syncService.syncLocation();
} else {
Log.d(TAG, "User is not logged in so discarding sync ....");
stopSelf();
}
stopSelf();
}
- 'syncService.syncLocation();' 最终会执行一些计算和多次网络请求。