我正在尝试在单击通知操作时运行重试例程,为此,我创建了一个BroadcastReceiver
并将其注册到AndroidManifest
文件中。
在使用我正在使用的操作创建通知并使用PendingIntent
通知操作设置待定意图时。
当应用程序正在运行或在后台(未从最近的应用程序列表中删除)时,单击通知操作会立即接收到广播接收器。但是在杀死应用程序(从最近的应用程序列表中删除它)之后,广播接收器需要一些时间来触发。
以下是不同组件的代码片段。
AndroidManifest 文件
<receiver android:name=".Receiver.RetryStatusBroadcastReceiver" android:enabled="true" android:exported="false"/>
广播接收器
public class RetryStatusBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
}
}
通知触发代码
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());
}
我也尝试过扩展我的 BroadcastReceiver,WakefulBroadcastReceiver
但结果是一样的。我也尝试过删除android:enabled
和android:exported
标签,但这里似乎没有任何效果。