BroadcastReceiver第二次不起作用。

huangapple go评论82阅读模式
英文:

BroadcastReceiver doesn't work for the second time

问题

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

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>

我尝试使用AlarmManager来安排通知。当我安排一个通知时,它可以正常工作,但是当我安排两个通知时,第一个通知是正常的,但第二个通知不起作用。

我发现在几分钟后打开应用程序会通知第二个通知。我认为我的广播接收器可能有问题。

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

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>

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

英文:

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.

I figured out opening the app after few minutes will notify the second notification. I think something is wrong with my BroadcastReceiver

MainActivity.java

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

Notification.java

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

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

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

AndroidManifest.xml

&lt;receiver android:name=&quot;.NotificationClass&quot; &gt;&lt;/receiver&gt; 

I don't know what is wrong with my code. Can anybody help me with this?

答案1

得分: 1

Broadcast接收器以接收数据:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

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

        doNotificationAlertWorkHere(alertMessage);
    }
};

通过Android清单文件注册和取消注册广播以避免静态泄漏。(静态方式)

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

通过Context.registerReceiver()Context.unregisterReceiver()方法动态地注册和取消注册。

@Override
protected void onPause() {
    super.onPause();
    // 取消注册广播
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}

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

    // 注册广播
    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);

知识注释:广播接收器就像是发射炮弹进行命中,你需要确定要发射什么(例如,消息),在哪里发射(例如,活动)。加载和卸载炮筒以再次命中(例如,注册和取消注册)。

英文:

Broadcast receiver to receive the data:

private BroadcastReceiver mReceiver = new BroadcastReceiver() {

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

        doNotificationAlertWorkHere(alertMessage);
    }
};

Register & Unregister your broadcast to avoid static leaks.

via the Android manifest file. (Statically)

&lt;receiver android:name=&quot;YourBroadcastReceiverName&quot;&gt; &lt;/receiver&gt;

via the Context.registerReceiver() and Context.unregisterReceiver() methods. (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 = &quot;ALERT&quot;;

Intent intent = new Intent(Constants.ACTION);
intent.putExtra(&quot;type&quot;, &quot;SUP BRO. Stay Inside&quot;);
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). Load & unload the cannon to score another hit. (eg. Register & Unregister)

答案2

得分: 1

我已经尝试过,它是有效的。将您的通知代码添加到 onReceive 函数内。

广播接收器

class AlarmReceiver : BroadcastReceiver() {

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

        /*
        您的实现代码
        */
    }
}

清单文件

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

创建待定意图

val alarmManager = activity.getSystemService(Activity.ALARM_SERVICE) as AlarmManager
val alarmIntent = Intent(activity.applicationContext, AlarmReceiver::class.java) // AlarmReceiver1 = 广播接收器

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)
英文:

I have tried it and it is working. Add your notification code inside onReceive.

Broadcast Receiver

class AlarmReceiver : BroadcastReceiver() {

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

 /*
  Your implementation

   */
 }
}

Mainfest

    &lt;receiver
        android:name=&quot;.AlarmReceiver&quot;
        android:exported=&quot;true&quot;
        android:enabled=&quot;true&quot; /&gt;

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)

答案3

得分: 0

首先,确保每次创建通知时您的通知ID都不同。

其次,在清单文件中的 <receiver> 标签内部缺少 <intent-filter> 标签。请查阅此链接:https://developer.android.com/guide/components/broadcasts。

希望这能有所帮助!

英文:

First, make sure your notification Id is difference every single time you create a notification

Second, you miss tag intent-filter inside tag receive in manifest. pls check this https://developer.android.com/guide/components/broadcasts.

Hope this help!

huangapple
  • 本文由 发表于 2020年4月7日 03:47:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/61067797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定