【问题标题】:AlarmManager not working, delays schedule taskAlarmManager 不工作,延迟计划任务
【发布时间】:2019-05-15 15:01:59
【问题描述】:

我正在使用日历对话框询问用户时间的调度程序应用程序。然后我使用AlarmManager安排任务,你可以看到下面的代码。

    Log.d("SchedulerTag", "sendMessageLater: " + new Date(timeInMillis));
    Intent intent = new Intent(getApplicationContext(), AlarmReceiver.class);
    intent.putExtra("message", message_string);
    intent.putExtra("number", end_number);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
        Toast.makeText(this, "Message Scheduled Successfully", Toast.LENGTH_SHORT).show();
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
        Toast.makeText(this, "Message Scheduled Successfully", Toast.LENGTH_SHORT).show();
    }

在此之后,我使用 AlarmReceiver 类接收它,代码

public void onReceive(Context context, Intent intent) {
    //some code her
}

问题是,任务没有安排在正确的时间,无论选择什么时间,它只会在 10 分钟后被调用

我的清单包含接收器。我做错了什么?

【问题讨论】:

    标签: android scheduled-tasks alarmmanager scheduler


    【解决方案1】:

    您可以使用 JobScheduler 来重复任务。

    ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
    JobInfo.Builder builder = new JobInfo.Builder(15, serviceComponent);
    builder.setMinimumLatency(500);
    builder.setPersisted(true);
    
    JobScheduler jobScheduler = (JobScheduler)context.getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
    if (jobScheduler != null) {
        jobScheduler.schedule(builder.build());
    }
    

    TestJobService.class

    公共类 TestJobService 扩展 JobService {

    @Override
    public boolean onStartJob(JobParameters params) {
        // do your code when job scheduler fires.
        return false;
    }
    
    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }
    

    }

    【讨论】:

    • 我需要在哪里填写日期?
    • 计算到现在的毫秒数并将毫秒设置为最小延迟方法。
    • 适用于 API 21 我还需要低 API 支持
    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 2016-03-29
    • 2011-05-06
    • 1970-01-01
    • 2021-04-08
    • 2018-10-21
    • 2019-04-01
    • 2020-02-07
    相关资源
    最近更新 更多