How to wake up my intended service every 5 minutes

I know this question has been asked before, but I didn't get any answer, I want to create an intent service that starts the thread all the time, but when I exit the application, my service stops, then the thread stops too. I need to create something to wake up the service every few minutes. or something to prevent the service from being killed even when the application is killed or closed.

this is how i start my service

Intent intent= new Intent(Intent.ACTION_SYNC,null,this,IntentServ.class);
startService(intent);

      

+3


source to share


3 answers


For this you can use AlarmManager

which can start your service every 1 hour. For example:



 AlarmManager mgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
 Intent notificationIntent = new Intent(context,
                UpdateService.class);
 PendingIntent pendingIntent=PendingIntent.getService(context, requestCode, Intent.parseIntent(), 0);
  mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
        System.currentTimeMillis(), AlarmManager.INTERVAL_HOUR, pendingIntent);

      

+6


source


Use normal Service

c android.app.AlarmManager

.



Don't need to use WakefulBroadcastReceiver

.

+1


source


AlarmManager

and PendingIntent

- this is what you need in this case. Below is an example:

AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);

      

/ * --- Create pending intent to be executed on wakeup --- * /

PendingIntent operation = getUpdatePolicyOperation();
am.set(AlarmManager.RTC, alarmTime, operation); // alarm time is millisecond time in milliseconds that the alarm should go off, using the appropriate clock (depending on the alarm type).

      

You can learn more about alarm mode AlarmManager

in here or take a tutorial in Here

Hope it helped.

+1


source







All Articles