【发布时间】:2020-08-15 22:06:04
【问题描述】:
很多关于这个主题的问题都有过时的答案(1-4 岁)。
How To give notifications on android on specific time?
How To give notifications on android on specific time in Android Oreo?
Repeat notification every day 12h
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 无法在准确的时间运行。
如何将其变成可靠的通知提醒,让我的应用在几乎每天同一时间运行,即使应用已关闭?
【问题讨论】:
-
只是作为未来任何人的便条。除了 Keivan.k 的解决方案外,我还发现我必须在调试模式下运行模拟器才能使后台通知正常工作。
标签: java android android-studio notifications alarmmanager