gpt4 book ai didi

java - 如何使用警报管理器设置通知

转载 作者:行者123 更新时间:2023-12-02 09:28:52 26 4
gpt4 key购买 nike

我想在主要 Activity 中按下按钮 10 秒后生成通知我尝试了很多方法但没有收到通知

这是我的主类中的代码

     btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
long when = System.currentTimeMillis() + 10000L;

AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
intent.putExtra("myAction", "mDoNotify");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);

}
});

和AlertReceiver类

if(intent.getStringExtra("myAction") != null &&
intent.getStringExtra("myAction").equals("notify")){
NotificationManager manager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher_background)
//example for large icon
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle("my title")
.setContentText("my message")
.setOngoing(false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Intent i = new Intent(context, MainActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(
context,
0,
i,
PendingIntent.FLAG_ONE_SHOT
);
// example for blinking LED
builder.setLights(0xFFb71c1c, 1000, 2000);
//builder.setSound(yourSoundUri);
builder.setContentIntent(pendingIntent);
manager.notify(12345, builder.build());
}

最佳答案

您的字符串不匹配:

intent.putExtra("myAction", "mDoNotify");
<...>
if(intent.getStringExtra("myAction") != null &&
intent.getStringExtra("myAction").equals("notify")){

此外,您必须创建通知 channel ,否则通知将不会在 Android 9+ 上显示

关于java - 如何使用警报管理器设置通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58132971/

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