奥利奥AlarmManager在后台不起作用

时间:2018-11-28 16:45:56

标签: android alarmmanager android-notifications android-8.0-oreo android-8.1-oreo

我想使用AlarmManager启动通知服务。但是,当在最近的任务层中滑动应用程序时,它永远不会起作用。我还尝试了Manifest中相应条目的JobIntentService和JobService,所有结果都导致了相同的问题:关闭了我之后,Notification或startActivity()不会被调用(有时!也许在打ze模式下?)。应用程序。

现在,我想也许要回到AlarmManager,因为它似乎对这里的其他人有用。

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

            Intent intent = new Intent(getActivity(), AlertReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 1, intent, 0);

            if(Build.VERSION.SDK_INT <= 23)
            {
                alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeForAlarm, pendingIntent);//Alarm with setExact and AlertReceiver should be better than the old Alarm Manager
            }
            else
            {
                alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, timeForAlarm, pendingIntent);//Alarm with setExact and AlertReceiver should be better than the old Alarm Manager

            }
          }
        else
        {
            final AlarmManager alarm = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);

            Intent intent = new Intent(getActivity(), Service_Notification.class);

            PendingIntent startPendingIntent = PendingIntent.getService(getActivity(), 0, intent, 0);
            alarm.set(AlarmManager.RTC_WAKEUP, timeForAlarm, startPendingIntent);
        }

这是我的KitKat以上版本的AlertReceiver(我也尝试过扩展BroadCastReceiver)

public class AlertReceiver extends WakefulBroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        context.startService(new Intent(context, Service_Notification.class));
    }
}

那么,我现在该怎么办?预先谢谢你

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。自奥利奥(Oreo)以来,后台任务的政策似乎已发生了很大变化。您可以在Jetpack中检查WorkManager。大大简化了不同操作系统版本之间的用例。

OneTimeWorkRequest.Builder ob = new OneTimeWorkRequest.Builder(YourWorker.class)
    .setConstraints(constraints)
    .setInitialDelay(delayed, TimeUnit.MILLISECONDS)
    .addTag(yourWorkerTag);
WorkManager.getInstance().beginUniqueWork(orderTag, ExistingWorkPolicy.REPLACE, ob.build()).enqueue();

然后在YourWorker中启动您的通知服务。完成了!