Search code examples
androidservicealarmmanagertogglebutton

How to setup a toggle button that triggers a periodical service?


I need to implement the following function in my Android application: a toggle button that triggers off a periodical service.

Let me present the problem in a better way: I want a toggle button that has an "on" mode. In this mode I want to start a Service periodically (every 5 minutes for example). In the "off" mode the periodical Service is disabled. I suppose I need to use an AlarmManager service.

Can you provide me the guidelines (with code if it's possible) or a good tutorial to do this?

Thank in advance


Solution

  • private AlarmManager alarmManager; private PendingIntent pendingIntent;

    Use this created methods to on and off the service on click of toggle button. Also make sure to use AlarmManager as singleton.

    private void setService() {
    
                    try {
                        if (alarmManager != null) {
                            alarmManager.cancel(pendingIntent);
                        }
                    } catch (Exception e) {
    
                        e.printStackTrace();
                    }
                    Intent intent = new Intent(this, MyBroadCastReceiver.class);
    
                    pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
    
                    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); //
                            // 60 seconds i.e 1 min 
                    long time = 60 * 1000;
    
                    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                            SystemClock.elapsedRealtime() + time, time, pendingIntent);
    
                }
    

    To remove the serviceUpdates use the below method:

     private void removeService() {
                try {
                    if (alarmManager != null) {
                        alarmManager.cancel(pendingIntent);
                    }
                } catch (Exception e) {
                    // TODO: handle exception
                    e.printStackTrace();
                }
            }
    

    Now the Broadcast class is supposed to be as shown below:

    public class MyBroadCastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
    
    
            Log.d("test_log", "broadcast worked ");
    
        }
    }
    

    Now comes the manifest declaration of your receiver:

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