通知生成器会在随机时间显示通知

时间:2018-11-14 09:42:40

标签: android alarmmanager android-notifications

我正在开发一个应用,用户希望在指定的时间后显示通知,例如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());
}

请告诉我我在做什么错。

1 个答案:

答案 0 :(得分:2)

您可以使用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

public class TestJobService extends JobService {

    @Override
    public boolean onStartJob(JobParameters params) {
        // create notification here
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters params) {
        return true;
    }
}