Search code examples
androidservicealarmmanager

Start service if it's not running with AlarmManager


i've got service which is started by AlarmManager likes this

Intent in = new Intent(SecondActivity.this,BotService.class);
                    PendingIntent pi = PendingIntent.getService(SecondActivity.this, 9768, in,PendingIntent.FLAG_UPDATE_CURRENT);

                    AlarmManager alarms = (AlarmManager) SecondActivity.this.getSystemService(Context.ALARM_SERVICE);
                    alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pi);

When service is started it sets AlarmManager again, i do this because i need recurring service in random intervals.

That is done by this:

Intent in = new Intent(BotService.this, BotService.class);
            PendingIntent pi = PendingIntent.getService(BotService.this, 9768,
                    in, PendingIntent.FLAG_UPDATE_CURRENT);

            AlarmManager alarms = (AlarmManager) BotService.this.getSystemService(Context.ALARM_SERVICE);
            alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+ (attack_interval * MINS) + attack_interval_min, pi);

My service could last for random period of time, how to start service by AlarmManager if service is not running?

And if it is running i need to set AlarmManager again because in other way my service wouldn't start again. Thank you for your answers. If anything unclear please ask.


Solution

  • If you look at the documentation. When the Service starts, it has a startID, this can be used for determining the number of service instances that are running at that given time.

    Refer:

    public int onStartCommand (Intent intent, int flags, int startId)
    
    Added in API level 5
    Called by the system every time a client explicitly starts the service by calling startService(Intent), providing the arguments it supplied and a unique integer token representing the start request. Do not call this method directly.
    
    For backwards compatibility, the default implementation calls onStart(Intent, int) and returns either START_STICKY or START_STICKY_COMPATIBILITY.
    
    If you need your application to run on platform versions prior to API level 5, you can use the following model to handle the older onStart(Intent, int) callback in that case. The handleCommand method is implemented by you as appropriate: