Search code examples
androidalarmmanagerandroid-alarmsoptimistic-locking

Want to repeat alarm in every 20 seconds


AlaramManager will be working fine but repeat time vary device to device

public void StartMoniterning() {
    try {
        Alarammanager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, AppMoniteringBroadCastReceiver.class);
        alarmIntent.putExtra("id", 1314);
        pendingIntent = PendingIntent.getBroadcast(this, 1314, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        Alarammanager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP ,
                0, 2*10000,
                pendingIntent);
        Toast.makeText(this, "Starting Monitering",
                Toast.LENGTH_LONG).show();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

Check my code snippet for cancellation the AlaramManager.

private void cancelAlaram() {
    try {
        Alarammanager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent i = new Intent(getBaseContext(), AppMoniteringBroadCastReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getApplicationContext(), 1314, i, 0);

        Alarammanager.cancel(pendingIntent);
        pendingIntent.cancel();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Check AlaramManager Running or not.

public boolean isAlaramManagerExist() {
    Intent myIntent = new Intent(HomeActivity.this, AppMoniteringBroadCastReceiver.class);
    return (PendingIntent.getBroadcast(HomeActivity.this, 1314, myIntent, PendingIntent.FLAG_NO_CREATE) != null);
}

Solution

  • Android's become a real bitch when it comes to behavior that can potentially be misused and drain battery life. I've had a lot of trouble with repeating alarms going off at the wrong times. What my app does (and it works flawlessly for the most part, more on that later) is it registers a non-repeating alarm and then in the alarm receiver class (in your case it's AppMoniteringBroadCastReceiver) when it receives the alarm it registers the same alarm again at the proper time in the future (in your case 20 seconds later). So instead of a repeating alarm it has a chain of non-repeating alarms.

    My app registers the non-repeating alarms in three ways depending on the Android version: by using AlarmManager.set() for Android versions lower than KitKat, it uses AlarmManager.setExact() for anything from Kitkat until Marshmallow, finally it uses AlarmManager.setExactAndAllowWhileIdle() for Marshmallow and up.

    This is accurate to the second on most Android devices, but there may be battery optimization features (like Doze or other vendor implemented) that will mess with this and prevent your app from receiving the alarm. You can't do anything about that except tell users how to exempt your app from Doze or other vendor-specific implementations.