[好,所以从某种意义上说,这是一种重复,例如以下问题:Using Service to run background and create notification,我从中获取了代码并让其完成了我需要做的工作。
但是所有答案现在都存在问题,他们希望使用现在已贬值的WakefulBroadcastReceiver
。我了解我现在需要使用JobService,因此我尝试更新上一篇文章中的代码,使其看起来像这样(本教程的一部分https://www.vogella.com/tutorials/AndroidTaskScheduling/article.html)
public class NotificationEventReceiver extends JobService {
private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
private static final int NOTIFICATIONS_INTERVAL = 1;
public static void setupAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent alarmIntent = getStartPendingIntent(context);
alarmManager.setRepeating(AlarmManager.RTC,
getTriggerAt(new Date()),
NOTIFICATIONS_INTERVAL * AlarmManager.INTERVAL_DAY,
alarmIntent);
}
private static long getTriggerAt(Date now) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(now);
//calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
calendar.set(Calendar.HOUR_OF_DAY, 5);
calendar.set(Calendar.MINUTE, 0);
return calendar.getTimeInMillis();
}
@Override
public boolean onStartJob(JobParameters params) {
Intent service = new Intent(getApplicationContext(), NotificationIntentService.class);
getApplicationContext().startService(service);
setupAlarm(getApplicationContext()); // reschedule the job
return true;
}
@Override
public boolean onStopJob(JobParameters params) {
return true;
}
private static PendingIntent getStartPendingIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public static PendingIntent getDeleteIntent(Context context) {
Intent intent = new Intent(context, NotificationEventReceiver.class);
intent.setAction(ACTION_DELETE_NOTIFICATION);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
}
然后在Android清单中
<service
android:name=".NotificationEventReceiver"
android:label="Notification Service"
android:permission="android.permission.BIND_JOB_SERVICE" />
运行时,我不再收到任何通知,因此我显然做错了什么,但是我无所适从,因为我需要做的事情。
我最近遇到了这个问题,我使用广播接收器解决了我的问题。