Search code examples
androidandroid-intentandroid-broadcastintentserviceandroid-broadcastreceiver

Android: which kind of Broadcast/Receiver combination should I use?


In my app, I want to kick off an timer that triggers an action every x minutes, regardless if the user is currently in the app or not. I have been reading around and am not sure which combo of Broadcast and Receiver types I should use - any guidance would be helpful.

Example of user actions:

  1. User hits a button, sets initial timer (alarm)
  2. Timer is reached, trigger an action and set the timer again
  3. Repeat until it has run for x minutes

Solution

    1. when the user hits button set alarm as

      AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
      am.setRepeating (AlarmManager.Type, 
               long triggeringtime, 
               long interval, 
               PendingIntent operation);
      

    here triggeringtime is how to time it shud take to take an action

    and interval how to much time it would take to do the same.

    here operation is the Intent which you need to execute like it may be an activity or Service you can Define it as

        operation = PendingIntent.getActivity( context, 0, intent or service, 0);
    

    2 and 3 step will be continuously run thats what the alarm manager does.

    This alarm continues repeating until explicitly removed with

      cancel(AlarmManager.OnAlarmListener). 
    

    I am a beginner Sry if i wrong. Hope it helps!