Search code examples
androidservicealarmmanagerandroid-5.0-lollipop

Can't set AlarmManager to repeating one


I'm trying to set an Alarm to wakes up every 30s but it doesn't work. It does just 1 time at the beginning. I'm not sure if i've to use setInexactRepeating or setRepeating or setExact(and recall the method); and if i should use ELAPSED_REALTIME_WAKEUP or RTC_WAKEUP.

public void onClick(View view) {
    alarmMethod(this);
}

public static void alarmMethod(Context context) {
    Intent myIntent = new Intent(context, LocalWordService.class);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0 ,myIntent, 0);

    Calendar cur_cal = new GregorianCalendar();
    cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar

    Calendar cal = Calendar.getInstance();        

    cal.set(Calendar.MINUTE, cur_cal.get(Calendar.MINUTE) + 1);
    cal.set(Calendar.SECOND, 30);        

    alarmManager.cancel(pendingIntent);
    alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000 * 30, pendingIntent);
    Log.d("MainActivity", "Alarm at = " + cal.getTime().toString());
    Toast.makeText(context, "Start Alarm", Toast.LENGTH_SHORT).show();

}

And my Service is:

public class LocalWordService extends Service {

@Override
public IBinder onBind(Intent arg0) {
    Toast.makeText(getApplicationContext(), "onBind", Toast.LENGTH_SHORT).show();
    return null;
}

@Override
public void onCreate(){
    Toast.makeText(getApplicationContext(), "WAKE UP!!!", Toast.LENGTH_SHORT).show();
    Log.d("Service", "ActualTime : " + DateFormat.getDateInstance().getCalendar().getTime().toString());
    //MainActivity.alarmMethod(getApplicationContext());
}

}

PS: I'm testing with an Android Lollipop device. (5.0.2)


Solution

  • put your code from onCreate() to onStartCommand()

    because I think you are using startService() in onReceive() of your alarm receiver. and first time it create your service and call onCreate() but after 30 seconds when startService() get called then service is already created and hence it call onStartCommand().

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
       Toast.makeText(getApplicationContext(), "WAKE UP!!!", Toast.LENGTH_SHORT).show();
        Log.d("Service", "ActualTime : " + DateFormat.getDateInstance().getCalendar().getTime().toString());
        //MainActivity.alarmMethod(getApplicationContext());
        return super.onStartCommand(intent,flags,startId);
    }