首页 > 解决方案 > 通知生成器在随机时间显示通知

问题描述

我正在开发一个应用程序,用户希望在他指定的时间之后显示通知,例如 1 小时、2 小时、30 分钟、40 分钟,无论他选择什么。但我面临的问题是通知出现在随机时间。有时它会在用户选择的 1 小时后出现,有时它会在 30 分钟后出现。

触发广播的代码

long intervalSpan = timeInterVal * 60 * 1000; // timeInterVal is the value user enters in minutes
    Calendar calendar = Calendar.getInstance();
    Intent intentAlarm = new Intent(this, AlarmBroadCastReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalSpan, pendingIntent);

// also tried alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), intervalSpan, pendingIntent);

在广播中显示通知的代码

 builder = new NotificationCompat.Builder(context)
            .setContentTitle(title)
            .setContentText(content)
            .setSound(mReminderSound ? alarmSound : null)
            .setLights(mLed ? 0xff00ff00 : 0, 300, 100)
            .setVibrate(mVibraion ? vibrate : new long[]{0L})
            .setPriority(2)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(content))
            .addAction(action)
            .setSmallIcon(R.mipmap.ic_stat_call_white)
            .setColor(Color.BLUE)
            .setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
                    R.drawable.ic_launcher_logo))
            .addAction(actionSnooze);


    builder.setContentIntent(pendingIntent);
    createNotification(contextl, builder);

}


private void createNotification(Context context, NotificationCompat.Builder builder) {
    mNotificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
    mNotificationManager.notify(Constants.NOTIFICATION_ID,
            builder.build());
}

请告诉我我做错了什么。

标签: androidalarmmanagerandroid-notifications

解决方案


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

    ComponentName serviceComponent = new ComponentName(context, TestJobService.class);
    JobInfo.Builder builder = new JobInfo.Builder(15, serviceComponent);
    builder.setPeriodic(20*60*1000); // this will repeat after every 20 minutes
    builder.setPersisted(true);

    JobScheduler jobScheduler = (JobScheduler)context.getApplicationContext().getSystemService(JOB_SCHEDULER_SERVICE);
    if (jobScheduler != null) {
        jobScheduler.schedule(builder.build());
    }

TestJobService.class

公共类 TestJobService 扩展 JobService {

    @覆盖
    公共布尔 onStartJob(JobParameters 参数){
        // 在此处创建通知
        返回假;
    }

    @覆盖
    公共布尔 onStopJob(JobParameters 参数){
        返回真;
    }
}    

推荐阅读