Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alarm Manager not firing when app is killed on Android 7 (One Plus 3T)

Since the introduction Doze Mode and App StandBy managing alarms have changed. The problem I'm facing is my alarm manager fires correctly on KitKat, Lolipop and Marshmellow devices but above API 23 it does not fire unless the app is in foreground or background. But if the app is killed, the alarms are stopped.

Checked out Google Keep Application on my Android 7, turns out it does the same.

But Google Calendar fires regardless of whether the app is killed or not.

Done some reading and found out setExactAndAllowWhileIdle method on the alarm manager ensures to break the doze mode and trigger your alarm.

But it does not work, is there anything I'm missing here?

Here's my code:

Intent alertIntent = new Intent(this, NotificationPublisher.class);

    alertIntent.putExtra("Hello", "Meal Time");

    AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);

    int id = (int) System.currentTimeMillis();

    if (Build.VERSION.SDK_INT < 23) {
        if (Build.VERSION.SDK_INT >= 19) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, delay, PendingIntent.getBroadcast(this, id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, delay, PendingIntent.getBroadcast(this, id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
        }
    } else {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, delay, PendingIntent.getBroadcast(this, id, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
    }

Broadcast Receiver:

public class NotificationPublisher extends WakefulBroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    String message = intent.getStringExtra("Hello");
    Log.d("Called", "Meal Time");
}

Manifest:

    <uses-permission android:name="android.permission.WAKE_LOCK" />
        <receiver android:name=".NotificationPublisher" />
like image 710
Veeresh Charantimath Avatar asked Jun 27 '17 05:06

Veeresh Charantimath


1 Answers

Because of battery optimisation it is not working,i turned off the battery optimisation of particular app, it is working fine in oneplus 3.

You wanna white-list your app from battery optimisation programatically, check this link stackoverflow.com/a/42651399/3752079

like image 54
Brahmam Yamani Avatar answered Oct 23 '22 03:10

Brahmam Yamani