gpt4 book ai didi

java - BroadcastReceiver 第二次不起作用

转载 作者:行者123 更新时间:2023-12-04 10:15:44 28 4
gpt4 key购买 nike

我正在尝试使用 AlarmManager 安排通知当我安排一个通知时它工作得很好,但是当我安排两个通知时,第一个通知没问题,但第二个通知不起作用。

我发现几分钟后打开应用程序会通知第二个通知。我认为我的 BroadcastReceiver 有问题

MainActivity.java

Intent intent = new Intent(context,NotificationClass.class);
intent.putExtra("notification_id", id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,id,intent,PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),pendingIntent);

通知.java
public class NotificationClass extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int id = intent.getIntExtra("notification_id",0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"1")
.setContentTitle("Notification")
.setContentText("Content")
.setSmallIcon(R.drawable.notif_ic);

Notification notification = builder.build();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel("1","test", NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(id,notification);
}

AndroidManifest.xml
<receiver android:name=".NotificationClass" ></receiver> 

我不知道我的代码有什么问题。有人可以帮我解决这个问题吗?

最佳答案

广播接收器接收数据:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
String alertMessage = intent.getStringExtra("type");

doNotificationAlertWorkHere(alertMessage);
}
};

注册和取消注册您的广播以避免静态泄漏。

通过 Android list 文件。 (静态)
<receiver android:name="YourBroadcastReceiverName"> </receiver>

通过 Context.registerReceiver() 和 Context.unregisterReceiver() 方法。 (动态)
 @Override
protected void onPause() {
super.onPause();
// unregister broadcast
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}

@Override
protected void onResume() {
super.onResume();

// register broadcast
IntentFilter filter = new IntentFilter(Constants.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter);
}

发送广播,如:
// public static final String ACTION = "ALERT";

Intent intent = new Intent(Constants.ACTION);
intent.putExtra("type", "SUP BRO. Stay Inside");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

知识说明:- 广播接收器就像一门大炮来击中目标,您必须确定要发射什么(例如消息),在哪里发射(例如, Activity )。装载和卸载大炮以获得另一次命中。 (例如。注册和注销)

关于java - BroadcastReceiver 第二次不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61067797/

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