Search code examples
androidalarmmanager

Android AlarmManager fails to work


According to my knowledge, I should see the log "Alarm" in the Logcat after 20 seconds from starting the application, but it is not happening. What am I missing?

public class MainActivity extends Activity {
    private PendingIntent pendingIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent(MainActivity.this, MainActivity.class);
        pendingIntent = PendingIntent.getService(MainActivity.this, 1, intent, 1);

        AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        manager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, pendingIntent);

        Log.d("alarm", "alarm");
    }
}

Solution

  • Seems that you should use

    getActivity (Context context, int requestCode, Intent intent, int flags)
    

    As your Intent specifies the activity class, not service. Next, the last parameter (flags) can have values from constants in PendingIntent class. And as mentioned, second paramter should be 0 as it not used currently. Please refer this question for sample usage.