警报管理器在API 23之后未按预期启动服务

时间:2018-04-03 06:42:50

标签: android service alarmmanager backgroundworker

最近我将我的项目升级到26 Api级别。之后,报警经理不为我工作。我不知道问题是什么,但我猜警报根本不起作用,只要应用程序处于lolipop(> = M)以上的所有设备的后台。我已经解决了其他问题并且遵循了一些建议,例如'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();'终于做了一些计算和多个网络请求

2 个答案:

答案 0 :(得分:0)

更改您的if条件:

if(Build.VERSION.SDK_INT > 23)

为:

if(Build.VERSION.SDK_INT >= 23)

答案 1 :(得分:0)

使用此库解决了它 Evernote job scheduler library

它使用JobSchedulerGcmNetworkManagerAlarmManager,具体取决于您的Android操作系统版本。

Android Oreo的所有功能都向后兼容回到Ice Cream Sandwich。

JobRequest.Builder类有许多额外选项,例如您可以指定所需的网络连接,定期作业,使用捆绑包传递一些额外内容,在重新启动后恢复作业或在准确的时间运行作业。

实施例

     int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
        .setExecutionWindow(30_000L, 40_000L)
        .setBackoffCriteria(5_000L, JobRequest.BackoffPolicy.EXPONENTIAL)
        .setRequiresCharging(true)
        .setRequiresDeviceIdle(false)
        .setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
        .setExtras(extras)
        .setRequirementsEnforced(true)
        .setUpdateCurrent(true)
        .build()
        .schedule();