Android: Как исправить BroadcastReceiver в JobIntentService? - PullRequest
0 голосов
/ 25 мая 2018

У меня есть Activity с AlarmManager, который запускает BroadcastReceiver.BroadcastReceiver запускает JobIntentService для отправки уведомления пользователю.

Когда пользователь нажимает «CLEAR ALL» или проводит пальцем, чтобы отклонить уведомление, я хочу, чтобы setDeleteIntent () сбрасывал переменную счетчика totalMessages на ноль, который я установил в файле SharedPreferences.Это не обнуление.Что мне здесь не хватает?

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

1 Ответ

0 голосов
/ 25 мая 2018

Проблема в том, что реализация вашего широковещательного приемника для очистки уведомлений находится в пределах жизненного цикла задания.JobIntentService поручено показать уведомление и уйти, таким образом, получателю вещания.Но когда пользователь нажимает на CLEAR из уведомления, ожидающее намерение транслируется, но тогда некому его слушать.

Для решения я бы предложил вам создать отдельного широковещательного приемника и зарегистрировать его вваш AndroidManifest.xml.К тому времени твоя трансляция будет всегда прослушиваться, и ты сможешь исполнить то, что когда-либо в пределах ..

...