Android:如何修复 JobIntentService 中的 BroadcastReceiver? [英] Android: How to fix BroadcastReceiver in JobIntentService?

查看:54
本文介绍了Android:如何修复 JobIntentService 中的 BroadcastReceiver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有 AlarmManager 的 Activity,它会触发 BroadcastReceiver.BroadcastReceiver 触发 JobIntentService 以向用户发送通知.

I have an Activity with an AlarmManager that fires a BroadcastReceiver. The BroadcastReceiver fires a JobIntentService to send a Notification to the user.

当用户点击全部清除"或滑动以关闭通知时,我希望 setDeleteIntent() 将我在 SharedPreferences 文件中设置的计数器变量totalMessages"重置为零.它不会重置为零.我在这里错过了什么?

When the user taps "CLEAR ALL" or swipes to dismiss the Notification, I want the setDeleteIntent() to reset a counter variable "totalMessages" to zero that I set up in a SharedPreferences file. It is not resetting to zero. What am I missing here?

public class AlarmService extends JobIntentService {

    static final int JOB_ID = 9999;
    public static final String NOTIFICATIONS_COUNTER = "NotificationsCounter";
    private static final int REQUEST_CODE_DELETE_INTENT = 1;
    int totalMessages = 0;

    static void enqueueWork(Context context, Intent work) {
        enqueueWork(context, AlarmService.class, JOB_ID, work);
    }

    @Override
    protected void onHandleWork(@NonNull Intent intent) {

        IntentFilter filter = new IntentFilter();
        filter.addAction("notification_cleared");
        registerReceiver(receiver, filter);

        sendNotification();
    }

    private void sendNotification() {

        int notifyID = 1;

        NotificationManager notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        SharedPreferences sp = getSharedPreferences(NOTIFICATIONS_COUNTER, Context.MODE_PRIVATE);
        totalMessages = sp.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
        SharedPreferences.Editor editor = sp.edit();
        editor.putInt("total-messages", ++totalMessages);
        editor.apply();

        NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setDefaults(Notification.DEFAULT_ALL)
            .setSmallIcon(R.drawable.ic_announcement_white_24dp)
            .setContentText("")
            Intent i = new Intent(this, AlarmService.class);
            i.setAction("notification_cleared");
            PendingIntent deleteIntent = PendingIntent.getBroadcast(this,REQUEST_CODE_DELETE_INTENT,i,PendingIntent.FLAG_CANCEL_CURRENT);
            mBuilder.setDeleteIntent(deleteIntent);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mBuilder.setSubText(String.valueOf(totalMessages));
        }
        else {
            mBuilder.setNumber(totalMessages);
        }

        if (notificationManager != null) {
            notificationManager.notify(notifyID, mBuilder.build());
        }
    }

    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action != null) {
                if (action.equals("notification_cleared")) {

                // Reset the Notifications counter ("total-messages") to zero since the user
                // clicked on "CLEAR ALL" Notification or swiped to delete a Notification.
                SharedPreferences sp1 = getSharedPreferences(NOTIFICATIONS_COUNTER, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp1.edit();
                editor.clear();
                editor.apply();
                totalMessages = sp1.getInt("total-messages", 0); //initialize to 0 if it doesn't exist
                editor.putInt("total-messages", totalMessages);
                editor.apply();
                }
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();

        unregisterReceiver(receiver);
    }
}

推荐答案

问题是广播接收器清除通知的实现在作业的生命周期内.JobIntentService 的任务是显示通知并离开广播接收器.但是当用户点击通知中的 CLEAR 时,待处理的意图会被广播,但没有人可以听到它.

The problem is that your broadcast receiver's implementation to clear notifications is within the life-cycle of job. JobIntentService is tasked to show notification and go away thus the broadcast receiver. But when the user clicks on the CLEAR from notification, the pending intent is broadcasted but then there's no one to listen to it.

对于解决方案,我建议您创建一个单独的广播接收器并在您的 AndroidManifest.xml 中注册它.届时您的广播将始终被收听,您可以在其中执行任何操作..

For a solution, I would suggest you to create a separate broadcast receiver and register it in your AndroidManifest.xml. By then your broadcast will always be listened and you can perform what ever within..

这篇关于Android:如何修复 JobIntentService 中的 BroadcastReceiver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆