简体   繁体   English

BroadcastReceiver第二次不工作

[英]BroadcastReceiver doesn't work for the second time

I'm trying to schedule notifications with AlarmManager It works perfectly when I schedule one notification but when I schedule two notification, the first notification is okay but the second one not works.我正在尝试使用AlarmManager安排通知当我安排一个通知时它可以完美运行,但是当我安排两个通知时,第一个通知可以,但第二个通知不起作用。

I figured out opening the app after few minutes will notify the second notification.我发现几分钟后打开应用程序会通知第二个通知。 I think something is wrong with my BroadcastReceiver我认为我的 BroadcastReceiver 有问题

MainActivity.java 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);

Notification.java通知.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 AndroidManifest.xml

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

I don't know what is wrong with my code.我不知道我的代码有什么问题。 Can anybody help me with this?有人可以帮我吗?

Broadcast receiver to receive the data:广播接收器接收数据:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

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

        doNotificationAlertWorkHere(alertMessage);
    }
};

Register & Unregister your broadcast to avoid static leaks.注册和注销您的广播以避免 static 泄漏。

via the Android manifest file.通过 Android 清单文件。 (Statically) (静态)

<receiver android:name="YourBroadcastReceiverName"> </receiver>

via the Context.registerReceiver() and Context.unregisterReceiver() methods.通过 Context.registerReceiver() 和 Context.unregisterReceiver() 方法。 (Dynamically) (动态)

 @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);
    }

Send Broadcast like:发送广播,如:

// public static final String ACTION = "ALERT";

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

Knowledge Note:- Broadcast receiver is like a Cannon-fire to score a hit, you have to determine what to fire (eg. msg), where to fire (eg. activity).知识提示:- 广播接收器就像炮火一样要得分,您必须确定要发射什么(例如 msg),在哪里发射(例如活动)。 Load & unload the cannon to score another hit.加载和卸载大炮以再次命中。 (eg. Register & Unregister) (例如注册和注销)

I have tried it and it is working.我已经尝试过了,它正在工作。 Add your notification code inside onReceive.在 onReceive 中添加您的通知代码。

Broadcast Receiver广播接收器

class AlarmReceiver : BroadcastReceiver() {

override fun onReceive(context: Context, intent: Intent) {

 /*
  Your implementation

   */
 }
}

Mainfest主祭

    <receiver
        android:name=".AlarmReceiver"
        android:exported="true"
        android:enabled="true" />

Creating pending intents创建待处理的意图

val alarmManager = activity.getSystemService(Activity.ALARM_SERVICE) as AlarmManager
        val alarmIntent = Intent(activity.applicationContext, AlarmReceiver::class.java) // AlarmReceiver1 = broadcast receiver

        val calendar = Calendar.getInstance()
        calendar.timeInMillis = timeInMilliSeconds

        val pendingIntent = PendingIntent.getBroadcast(activity, timeInMilliSeconds.toInt(), alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT)
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.timeInMillis, pendingIntent)

First, make sure your notification Id is difference every single time you create a notification首先,确保每次创建通知时您的通知 ID 都不同

Second, you miss tag intent-filter inside tag receive in manifest.其次,您错过了清单中标签接收内的标签意图过滤器。 pls check this https://developer.android.com/guide/components/broadcasts .请检查此https://developer.android.com/guide/components/broadcasts

Hope this help!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM