我正在尝试每天在确切时间显示一次通知。我为此https://github.com/evernote/android-job使用 Evernote Android Job 库。时间来自后端 API。当应用程序处于前台或后台时,下面的代码工作正常。但是,当应用程序长时间(约 1 分钟)被终止或重新启动后,我不会在 One Plus 5T(牛轧糖)和 Oppo 设备(Mashmallow)上收到通知。此外,有时当我重新启动应用程序时,我会立即收到所有失败的通知。Asus Zenfone Max (Mashmallow) 一切正常。在华硕的每个场景中都会触发警报(前台、后台、屏幕锁定甚至重新启动)
以下是一加 5T 的 adb log
//当应用程序被杀死并且在闹钟预定时间之前
Shikhars-MacBook-Pro:HOGAndroid_New shikhardeep$ adb shell dumpsys alarm | grep "com.tf.eros.faythTv"
ELAPSED_WAKEUP #0: Alarm{3a8c0ae type 2 when 1118303576 com.tf.eros.faythTv}
tag=*walarm*:com.tf.eros.faythTv/com.evernote.android.job.v14.PlatformAlarmReceiver
operation=PendingIntent{e233e4f: PendingIntentRecord{217c9dc com.tf.eros.faythTv broadcastIntent}}
ELAPSED_WAKEUP #0: Alarm{44439ba type 2 when 1118303589 com.tf.eros.faythTv}
tag=*walarm*:com.tf.eros.faythTv/com.evernote.android.job.v14.PlatformAlarmReceiver
operation=PendingIntent{a7f706b: PendingIntentRecord{a45a7c8 com.tf.eros.faythTv broadcastIntent}}
u0a355:com.tf.eros.faythTv +1s718ms running, 4 wakeups:
*walarm*:com.tf.eros.faythTv/com.evernote.android.job.v14.PlatformAlarmReceiver
//当应用程序被杀死并且刚刚在闹钟预定时间之后
Shikhars-MacBook-Pro:HOGAndroid_New shikhardeep$ adb shell dumpsys alarm | grep "com.tf.eros.faythTv"
u0a355:com.tf.eros.faythTv +1s722ms running, 6 wakeups:
*walarm*:com.tf.eros.faythTv/com.evernote.android.job.v14.PlatformAlarmReceiver
代码
public class ShowHoroscopeNotificationJob extends Job {
public static final String TAG = "HOROSCOPE_NOTIFICATION";
public ShowHoroscopeNotificationJob() {
super();
}
@Override
protected void onReschedule(int newJobId) {
super.onReschedule(newJobId);
}
@NonNull
@Override
protected Result onRunJob(@NonNull Params params) {
try {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getContext(), "HOG_NOTIFICATION")
.setSmallIcon(R.drawable.notification_icon)
.setLargeIcon(BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.ic_launcher))
.setColor(ContextCompat.getColor(getContext(), R.color.colorPrimary))
.setContentTitle("Horoscope Reminder")
.setContentText("Check out Daily Horoscope !!!")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(new Random().nextInt(40) + 1, mBuilder.build());
schedule(getExactTime(ZPreferences.getHoroscopeReminderTime(getContext()))); //again calling schedule() as setExact() can't be periodic
return Result.SUCCESS;
}
} catch (Exception e) {
e.printStackTrace();
return Result.RESCHEDULE;
}
}
public static void schedule(long exactInMs) {
if (exactInMs != 0L) {
new JobRequest.Builder(ShowHoroscopeNotificationJob.TAG)
.setExact(exactInMs)
.build()
.schedule();
}
}