android - 通知生成器在随机时间显示通知
问题描述
我正在开发一个应用程序,用户希望在他指定的时间之后显示通知,例如 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());
}
请告诉我我做错了什么。
解决方案
您可以使用 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 参数){ 返回真; } }
推荐阅读
- regex - 用于 Int* 的 Z3 正则表达式
- css - 如何解决这个 sass 插值问题
- c++ - 关于 std::distance 和 std::istream_iterator 的问题
- ios - 如何让视图跟随我的手指移动?方向是从左到右
- python-3.x - 更新字典中的列表添加到每个键 Python3 中的列表
- java - 监控java本机内存
- puppeteer - Puppeteer:如何在表单中选择选项
- nlp - 带有 Spacy 的中文文本的 POS 标记和 NER
- python - 在 add_widget 函数上的 Python/Kivy 崩溃
- android - 如何将 Google-Analytics 迁移到 Firebase-Analytics?