Как отправить получателя из другого BroadcastReceiver?

Я хочу сохранить время уведомления, которое я установил, даже после BOOT_COMPLEDTED. Я просто делаю DeviceBootReceiver, который уведомляет BOOT_COMPLETED, и ReminderReceiver, который уведомляет пользователя с уведомлением. Мой код такой.

УстройствоБоттомРесивер

public class DeviceBootReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, Intent intent) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
                Toast.makeText(context, "BOOT_COMPLETED", Toast.LENGTH_SHORT).show();

                SharedPreferences sharedPreferences = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE);

                Calendar now = Calendar.getInstance();
                Calendar reminder = new GregorianCalendar();
                reminder.setTimeInMillis(sharedPreferences.getLong("reminder", Calendar.getInstance().getTimeInMillis()));

                if (now.after(reminder)) {
                    reminder.add(Calendar.DATE, 1);
                }

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                        reminder.getTimeInMillis(),
                        AlarmManager.INTERVAL_DAY,
                        PendingIntent.getBroadcast(context, 0, new Intent(context, ReminderReceiver.class), 0));


            }
        }
    }
}

НапоминаниеПолучатель

public class ReminderReceiver extends BroadcastReceiver {

    private static final String REMINDER_CHANNEL = "reminder";

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "ReminderReceiver", Toast.LENGTH_SHORT).show();

        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(REMINDER_CHANNEL, "channel name", NotificationManager.IMPORTANCE_HIGH);
            notificationManager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, REMINDER_CHANNEL);

        PendingIntent mainIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);

        builder.setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Reminder")
                .setContentText("This is time for you")
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setContentIntent(mainIntent)
                .setPriority(NotificationCompat.PRIORITY_MAX);

        notificationManager.notify(2, builder.build());

        Calendar reminder = Calendar.getInstance();
        reminder.add(Calendar.DATE, 1);

        SharedPreferences.Editor editor = context.getSharedPreferences(context.getPackageName(), Context.MODE_PRIVATE).edit();
        editor.putLong("reminder", reminder.getTimeInMillis());
        editor.apply();
    }
}

В DeviceBottReceiver, когда я загружаю свой мобильный телефон, всплывающее сообщение "BOOT_COMPLETED" появляется хорошо. Но в ReminderReceiver не вышло всплывающее сообщение "ReminderReceiver". Как я могу отправить приемник вещания на другой приемник вещания при перезагрузке мобильного устройства??


person hanjiman    schedule 07.02.2020    source источник
comment
Пожалуйста, проверьте и дайте мне знать, если проблема все еще сохраняется   -  person Kishan Maurya    schedule 07.02.2020
comment
Ваш ReminderReceiver, вероятно, не зарегистрирован в файле манифеста.   -  person grabarz121    schedule 07.02.2020
comment
Спасибо за совет. Но я уже зарегистрировал приемник в файле манифеста. <reciever android:name="DeviceBootReceiver" android:android:enable="false"> <intent-filter> <category android:name="android.intent.category.DEFAULT"/> <action android:name="android.intent.action.BOOT_COMPLETED"/> <action android:name="android.intent.action.QUICLBOOT_POWERON"/> </intent-filter> </receiver> <receiver android:name="ReminderReceiver"/>   -  person hanjiman    schedule 09.02.2020


Ответы (1)


Я использую ваш код, и он работает правильно. Для отладки используйте этот cmd

adb shell am broadcast -a android.intent.action.BOOT_COMPLETED -p  yourpackagename

В манифесте:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver android:name=".DeviceBootReceiver"
            android:enabled="true"
            android:exported="true"
            android:label="BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>
        <receiver android:name=".ReminderReceiver"/>
person Kishan Maurya    schedule 07.02.2020