gpt4 book ai didi

android - 如何设置通知在 X 分钟后显示?

转载 作者:行者123 更新时间:2023-11-29 02:35:47 25 4
gpt4 key购买 nike

我已经设法让我的通知在按下按钮时弹出,但我现在想进一步开发它,以便在按下按钮后 X 分钟(或 Y 小时)后通知不会弹出按下。

相关代码:

private void sendNotif() {
notification.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.avatar));
notification.setTicker("Kayla has returned");
notification.setWhen(System.currentTimeMillis());
notification.setContentTitle("Kayla has returned");
notification.setContentText("See what news she has to share");

Intent notifIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notifIntent, PendingIntent.FLAG_CANCEL_CURRENT);
notification.setContentIntent(pendingIntent);

NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, notification.build());
}

private void setNotif() {
Button btn = (Button) findViewById(R.id.notifBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendNotif();
}
});
}

我认为我需要以某种方式使用 AlarmManager,但我似乎无法将它合并到通知中......

最佳答案

您想将其设置为将来的特定时间。例如,如果当前是中午 12:00,而您希望在 10 分钟后到达,请将闹钟设置为中午 12:10。所以总是得到当前时间+你想等多久直到闹钟响起。这是一个例子。如果您想每 20 分钟重复一次该警报,我还包括在内。

private AlarmManager alarmMgr;
private PendingIntent alarmIntent;

private void setAlert(int hour, int minute) {
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);

alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
}

发送通知:

public void showNotification(Context context) {

NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Notification Title")
.setContentText("Notification Text");

NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

NotificationManager.notify().

mNotificationManager.notify(001, mBuilder.build());
}

在您当前调用 toast 的地方调用 sendNotification

确保从您的接收器获取上下文

@Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}

关于android - 如何设置通知在 X 分钟后显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47161546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com