我有一个带注释的应用程序。我在那里添加了通知(显示在状态栏中)。为了测试,我做了这样的设置,当您单击“绿色”按钮时,应用程序不仅会更改背景,还会向用户发送通知。但我想确保通知不是通过按下按钮发送给用户,而是在某个时间(例如,17:00)自动发送给用户,即使他没有打开应用程序。我该如何实施?为此,我提前准备了一个 BootCompletedReceiver,以便在设备启动后自动启动应用程序。接收者和通知代码将在下面。
引导完成接收器:
public class BootCompletedReceiver extends BroadcastReceiver {
public BootCompletedReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
}
}
}
发送通知代码:
...
public void onClickGreen(View view) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
v.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));
} else {
v.vibrate(500);
}
Intent notificationIntent = new Intent(Options.this, Options.class);
PendingIntent contentIntent = PendingIntent.getActivity(Options.this,
0, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(Options.this, CHANNEL_ID)
.setSmallIcon(R.drawable.ikon_for_calendar_1)
.setContentTitle("Напоминание")
.setContentText("Пора проверить заметки!")
.setSound(defaultSoundUri)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(contentIntent)
.setAutoCancel(true); // автоматически закрыть уведомление после нажатия
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(Options.this);
notificationManager.notify(NOTIFY_ID, builder.build());
}
使用警报管理器并将您的通知放在 NotifyService 类中