Search code examples
androidalarmmanager

Android - AlarmManager is not working after app is closed


I am using AlarmManager to call a function at a certain time. It is working successfully in Genymotion Emulator but not in a real device like Redmi, Honor, etc. Here is the Code.

     Intent intent = new Intent(CreateContact.this, DeleteContactReceiver.class);
     intent.putExtra("name", name.getText().toString());
     intent.putExtra("phone", phoneNumber.getText().toString());
     PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                getApplicationContext(), (int) System.currentTimeMillis(), intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                                + (selected * 60000), pendingIntent);

The min SDK version is 21.

EDIT: I tried to use setAndAllowWhileIdle but it still won't work.

Any Suggestions?


Solution

  • Use instead the androidx WorkManager library, is the replacement for all scheduling services.

    The WorkManager API is a suitable and recommended replacement for all previous Android background scheduling APIs

    https://developer.android.com/topic/libraries/architecture/workmanager

    What the WorkManager does is to wrap all the existing scheduling services, and use the most appropriate one according to what is available, API level, etc., even taking care of compatibility issues and system bugs.

    Some tutorials:

    https://medium.com/androiddevelopers/introducing-workmanager-2083bcfc4712

    https://www.programmersought.com/article/82731596284/

    https://medium.com/swlh/periodic-tasks-with-android-workmanager-c901dd9ba7bc