Search code examples
androidalarmmanagertoast

Hovering toast every 5 minutes


I've seen several examples on how to make some event to be repeated even when the app isnt running, but still I'm not sure if I got it.

With AlarmManager you can make your app to wake up to do something in some fixed interval without it consuming system resources between the periods, right? But can it be to show up a toast over your current activity instead of having an Activity with a layout for it?


Solution

  • AlarmReceiver class:

    public class AlarmReceiver extends BroadcastReceiver {
          @Override
          public void onReceive(Context context, Intent intent) {
    
                // this is where to start activity or service to launch toast message
             }
    
          }
    

    In activity or boot receiver:

    private static final int PERIOD = 60000; //or whatever you need for repeating alarm 
    
    AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);               
    Intent alIntent = new Intent(context, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, alIntent, 0);
    mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 60000, PERIOD, pi);  
    

    In AndroidManifest, add:

    <receiver android:name=".AlarmReceiver"></receiver>