AlarmManager не отменяет

Здравствуйте, я новичок в Android, и я пытаюсь создать приложение, которое будет проверять состояние батареи, когда устройство заряжается. если уровень заряда батареи больше, чем определено в настройках, будет отображаться уведомление и также прозвучит звонок.

Я сейчас просто тестирую и showing notification после каждого 30 secondпосле подключения устройства. согласно моей логикеalarm manger будет установлено, когда устройство подключено и будет cancel pending of alarm manager когда устройство plugged out.

Но не работает, уведомление тоже показывает after disconnecting device. Я не знаю, почему это происходит. Я попытался отменить отложенное рассмотрение, но это не работает.

пожалуйста, помогите мне, что здесь происходит.

CustomReceiver

public class CustomReceiver extends BroadcastReceiver {

    AlarmManager alarmManager;
    PendingIntent p;

    @Override
    public void onReceive(Context context, Intent intent) {
        String intentAction = intent.getAction();
        if (intentAction != null) {
            if (intentAction.equals(Intent.ACTION_POWER_CONNECTED)) {
                toast("Power Connected", context);
                setBatteryAlarm(context);
            }
            if (intentAction.equals(Intent.ACTION_POWER_DISCONNECTED)) {
                toast("Power Disconneted", context);
                cancelAlarm();
            }
        }
    }


    public void toast(String msg, Context context) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void setBatteryAlarm(Context context) {
        Intent notifyIntent = new Intent(context, BatteryCheckingReciever.class);
        p = PendingIntent.getBroadcast(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        long repeatInterval = 30000;
        long triggerTime = SystemClock.elapsedRealtime() + repeatInterval;

        alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerTime, repeatInterval, p);
    }

    private void cancelAlarm() {
        Log.e("kiran", "canceling alarm");
        if (alarmManager != null) {
            alarmManager.cancel(p);
            alarmManager = null;
        }
    }
}

Ресивер BroadCast для уведомлений

public class BatteryCheckingReciever extends BroadcastReceiver {

    NotificationManager notificationManager;
    int NOTIFICATION_ID = 0;
    String PRIMARY_CHANNEL = "battery_is_full";

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

        showNotificaiton(context);
    }

    private void showNotificaiton(Context context) {
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, PRIMARY_CHANNEL)
                .setSmallIcon(R.drawable.ic_battery_full)
                .setContentTitle(context.getString(R.string.battery_full))
                .setContentText(context.getString(R.string.battery_full_text))
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setAutoCancel(true)
                .setDefaults(NotificationCompat.DEFAULT_ALL);

        notificationManager.notify(NOTIFICATION_ID, builder.build());
    }
}

файл манифеста

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <receiver
            android:name=".BatteryCheckingReciever"
            android:enabled="true"
            android:exported="true"></receiver>
        <receiver
            android:name=".CustomReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

простите за плохой английский.

1 ответ

Решение

Это потому, что ваша ссылка на диспетчер аварийных сигналов и ожидаемое изменение намерения. Скорее всего, ваш диспетчер сигналов тревоги станет нулевым, но поскольку вы выполняете нулевую проверку, у вас нет ошибки. Вам нужно снова ссылаться на те же объекты

Измените свой код следующим образом:

  private void cancelAlarm() {

 alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent notifyIntent = new Intent(context, BatteryCheckingReciever.class);
 p = PendingIntent.getBroadcast(context, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);


        if (alarmManager != null) {
       Log.e("kiran", "canceling alarm");
            alarmManager.cancel(p);
            alarmManager = null;
        }
    }

/questions/27438398/kak-poluchit-i-otmenit-pendingintent/27438410#27438410

Другие вопросы по тегам