Android BroadcastReceiver firing with delay upon notification action click

468 views Asked by At

I am trying to run a Retry routine upon notification action click, for this, I have created a BroadcastReceiver and also registered it in the AndroidManifest file.

While creating the notification with action I am using PendingIntent and setting that pending intent with the notification action.

When the app is running or in the background (not removed from the recent apps list) then the broadcast receiver is received instantly upon clicking the notification action. But after killing the app (removing it from the recent app list) the broadcast receiver takes some to fire.

Below are the code snippets for different components.

AndroidManifest file

<receiver android:name=".Receiver.RetryStatusBroadcastReceiver" android:enabled="true" android:exported="false"/>

Broadcast receiver

public class RetryStatusBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        
    }
}

Notification firing code

Intent retryIntent = new Intent(this, RetryStatusBroadcastReceiver.class);
PendingIntent retryPendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), uniqueId + 1, retryIntent, 0);
NotificationCompat.Action retryAction = new NotificationCompat.Action(R.drawable.ic_retry, "Retry", retryPendingIntent);

NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, getString(R.string.background_syncing_notification_channel_id))
        .setSmallIcon(R.drawable.app_logo)
        .setPriority(Notification.PRIORITY_HIGH)
        .setDefaults(Notification.DEFAULT_ALL)
        .setContentTitle(notificationTitle)
        .setContentText(notificationMessage)
        .setStyle(new NotificationCompat.BigTextStyle().bigText(notificationMessage))
        .setAutoCancel(true)
        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
        .addAction(retryAction);

Intent intent = new Intent(this, HomeActivity.class);

PendingIntent activityPendingIntent = PendingIntent.getActivity(this, uniqueId, intent, PendingIntent.FLAG_ONE_SHOT);
notificationBuilder.setContentIntent(activityPendingIntent);
notificationBuilder.setAutoCancel(true);

NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (notificationManager != null) {
    notificationManager.notify(uniqueId, notificationBuilder.build());
}

I have also tried extending my BroadcastReceiver from WakefulBroadcastReceiver but the result is the same. I have also tried removing android:enabled and android:exported tags but nothing seems to work here.

0

There are 0 answers