创建一个安卓通知,即使应用程序关闭,也会在每天的某个时间重复出现



关于这个主题的很多问题都有过时的答案(1-4岁(。

如何在特定时间在android上发出通知?

如何在安卓奥利奥的特定时间在安卓上发出通知?

每天重复通知12小时

android的文档并没有让我找到具体的解决方案,但帮助我了解了AlarmManager和NotificationCompat。我的代码在MainActivity 中看起来像这样

Intent notifyIntent = new Intent(this, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, NOTIFICATION_REMINDER, 
notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hours);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, seconds);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,  calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY,
pendingIntent); 

我的BroadcastReceiver看起来像这个

public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d("Test", "RAN");
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
}

我的IntentService看起来像这个

public class MyNewIntentService extends IntentService {
private static final int NOTIFICATION_ID = 3;
public MyNewIntentService() {
super("MyNewIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("SH",
"Simple",
NotificationManager.IMPORTANCE_DEFAULT);
channel.setDescription("Notifs");
mNotificationManager.createNotificationChannel(channel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext(), "SH")
.setSmallIcon(R.mipmap.ic_launcher) // notification icon
.setContentTitle("Title") // title for notification
.setContentText("Message")// message for notification
.setAutoCancel(true); // clear notification after click
Intent intent1 = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent pi = PendingIntent.getActivity(this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
mNotificationManager.notify(0, mBuilder.build());
}
}

我已经将这些添加到我的AndroidManifest.xml中,就在我的应用程序标签中的活动下面

<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true" >
</receiver>
<service
android:name=".MyNewIntentService"
android:exported="false" >
</service>

通知会为我触发,但在应用程序关闭时不会。在android文档中,android似乎试图限制应用程序的后台处理量和时间,因此AlarmManager无法准确运行。

如何将其作为我的应用程序的可靠通知提醒,即使应用程序关闭,该应用程序也几乎每天在同一时间运行

您就快到了。非常接近,还有一件事。您应该使用startForeGroundService((,而不是startService((。在这种情况下,你的警报器会一直响。只有几个提示:

  1. 您应该在清单中声明前台服务
  2. 对于高于23的API级别,您必须使用alarmManager.setExactAndAllowWhileIdle

您也可以查看以获取更多信息。

更新:这个方法在小米红米note 8上很有效,但突然停止了!目前,对于自定义操作系统设备来说,它可能不是一个非常可靠的解决方案。希望谷歌能拿出一个可靠的解决方案。

最新更新