javaandroidandroid-workmanagerandroid-intentservice

what approach should i follow to make Timer service in android


I am working on an interval timer which make an alarm every interval (E.g. 30mins). I want to make the timer work in background or when device is in sleep and show a notification, I was told to use Intent Service but its deprecated. what should i use? -I want to support until API 21


Solution

  • You need to create a BroadcastReceiver. For example, using AlarmManager:

    int repeatTime = 30;  //Repeat alarm time in seconds
    AlarmManager processTimer = (AlarmManager)getSystemService(ALARM_SERVICE);
    Intent intent = new Intent(this, processTimerReceiver.class);   
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,  intent, 
    PendingIntent.FLAG_UPDATE_CURRENT);
    //Repeat alarm every second
    processTimer.setRepeating(AlarmManager.RTC_WAKEUP, 
    System.currentTimeMillis(),repeatTime*1000, pendingIntent); 
    

    And create your processTimerReciever class:

    //This is called every second (depends on repeatTime)
    public class processTimerReceiver extends BroadcastReceiver{
    
        @Override
        public void onReceive(Context context, Intent intent) {
            //Do something every 30 seconds
        }
    }
    

    Remember to register into Manifest:

    <receiver android:name="processTimer" >
       <intent-filter>
           <action android:name="processTimerReceiver" >
           </action>
       </intent-filter>
    </receiver>
    

    EDIT:

    If your app use an internet connection, you can send every 30 mins a notification using Firebase