Job Scheduler doesn't work if app is killed - android

I have looked at many other threads on this. However, none of this seems to help.
I need to set up job scheduler that runs everyday at 3PM.
Here is my service class:
public class AttendanceCheckScheduler extends JobService {
private AttendanceCheckTask mAttendanceCheckTask;
private static final String TAG = "AttendanceCheckScheduler";
#Override
public boolean onStartJob(JobParameters params) {
mAttendanceCheckTask = new AttendanceCheckTask();
mAttendanceCheckTask.execute();
jobFinished(params, false);
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
mAttendanceCheckTask.cancel(true);
return false;
}
private class AttendanceCheckTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// some long running task...
Toast.makeText(getApplicationContext(), "Task run", Toast.LENGTH_SHORT).show();
return null;
}
#Override
protected void onPostExecute(Void s) {
super.onPostExecute(s);
}
}
}
And this is how I am scheduling the job in ActivityHome.
public class ActivityHome extends AppCompatActivity {
private static final int JOB_ID = 100;
private JobScheduler jobScheduler;
protected JobInfo jobInfo;
private static final String TAG = "ActivityHome";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// other irrelevant codes here...
ComponentName componentName = new ComponentName(this, AttendanceCheckScheduler.class);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, componentName);
builder.setPeriodic(5000); // every 5 seconds for testing purpose...
builder.setPersisted(true);
jobInfo = builder.build();
jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(jobInfo);
Toast.makeText(this, "job scheduled", Toast.LENGTH_LONG).show();
}
}
Everythings seems to work fine and I am receiving the toast message Task run every 5 seconds as set above.
But when the app is killed (by clearing all task in multitask window), I stop receiving the toast messages.
How do I keep it running even if the app is killed ?
P.S: I want some task to perform once everyday at 3PM.

For background task for long time when your app is killed, you need to implement AlarmManager or WorkManager. WorkManager was in beta but now its ready only for Android X, just implement the dependency and copy paste WorkManager class code from google and put your task.
WorkManager latest dependency:
implementation "androidx.work:work-runtime:2.2.0"

I found this article. Here it says you have to call jobFinished() in your onPostExecute method of the asyncTask to let the system know the job is done.
jobFinished() requires two parameters: the current job, so that it
knows which wakelock can be released, and a boolean indicating whether
you’d like to reschedule the job. If you pass in true, this will kick
off the JobScheduler’s exponential backoff logic for you
I hope it helps.
Scheduling jobs like a pro with JobScheduler

There is an option not to kill the application, but it is very rude and it's the hack:
In your Manifest -> inside activity tag -> Add following line
android:excludeFromRecents="true"
Your app not show in recent apps history. So user can't kill the app.
Information is obtained by reference: https://code-examples.net/en/q/26c6cf8

Related

which way is better in android , JobScheduler or use timer?

I'm developing a chat application, For getting new messages in real-time we use a foreground service. (because of some situation we can't use FCM)
To be confident that clients are connected to the server, We send a ping to server every 1 minute with JobScheduler. Now we have a battery usage problem.
It's better to use CountDownTimer like bellow code in our foreground service :
CountDownTimer countDownTimerPingPeriodic;
public static boolean isPinging;
public void pingPeriodic(boolean fromService) {
if (countDownTimerPingPeriodic != null) {
countDownTimerPingPeriodic.cancel();
countDownTimerPingPeriodic = null;
}
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
long future = 75000;
countDownTimerPingPeriodic =
new CountDownTimer(60000, 60000) {
#Override
public void onTick(long l) {
}
#Override
public void onFinish() {
sendPing(false);
pingPeriodic(false);
}
};
isPinging = true;
countDownTimerPingPeriodic.start();
}
});
}
or it's better to use job service like bellow (Now we use bellow code and send ping in onStartJob):
public class ScheduleConnectionJob extends JobService {
private static final String TAG = "ScheduleConnectionJob";
private int i = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return Service.START_STICKY;
}
#Override
public boolean onStartJob(JobParameters params) {
//here I will send a ping to the server
jobFinished(params, true);
Util.scheduleJob(getApplicationContext()); // reschedule the job
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Util.scheduleJob(getApplicationContext());
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
Util.scheduleJob(getApplicationContext());
}}
And to call and repeat this service We use bellow code to repeat every 1 minute:
public class Util {
public static final long MinimumSchadulePeriodic = 15 * 60 * 1000 ;
// schedule the start of the service every 10 - 30 seconds
public static void scheduleJob(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ComponentName serviceComponent = new ComponentName(context, ScheduleConnectionJob.class);
JobInfo.Builder builder = new JobInfo.Builder(0, serviceComponent);
FileLog.i("Util:",
Thread.currentThread().getStackTrace()[2].getLineNumber() + " " +
"scheduleJob:scheduleJob");
builder.setMinimumLatency(MinimumSchadulePeriodic); // wait at least
builder.setOverrideDeadline(60 * 1000); // maximum delay
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY); // require unmetered network
JobScheduler jobScheduler = (JobScheduler) context.getSystemService(Context.JOB_SCHEDULER_SERVICE);
if (jobScheduler != null) {
jobScheduler.schedule(builder.build());
}
}
}}
You can also use WorkManager if it will be better in your case instead of JobScheduler.
The WorkManager API makes it easy to schedule deferrable, asynchronous tasks that are expected to run even if the app exits or device restarts.
Checkout this official documentation for further information ::
https://developer.android.com/topic/libraries/architecture/workmanager/
Also read this article https://medium.com/androiddevelopers/introducing-workmanager-2083bcfc4712
If you don't support below SDK 14 you can use workmanager. Otherwise see this guide to read about all the options.
Some extra resources on battery management: Doze and standby, power management restrictions, Analyzing power usage, Excessive wake-ups, Excessive network usage in background
Hope this helps you along a bit. I have to say that having your app ping the backend every minute seems a bit much. Unless its vital that your users receive their messages the instant they get send, it might be better to atleast bump that down to 5 or 10 minutes in background.

Scheduling persisted periodic job in Android

I want to schedule persisted periodic job which won't depend on system reboot. What is the best place to schedule the job? I think that putting scheduling into BOOT_COMPLETED Broadcast receiver will "reschedule" the job and it'll lead to unexpected behaviour (at least it's redundant, no?). May be MY_PACKAGE_REPLACED receiver?
Thanks for any ideas.
EDIT
I know this solution: https://stackoverflow.com/a/42084205/3974530
But I want PERSISTED job. I'm afraid of situation like: you have a periodic job which is running every 24 hours. And, for example, every 4 hours you reboot your device. So after each reboot the job will be rescheduled and... Your job will never be executed because the timer has been reset. Am I right?
The question is about JobScheduler only!
BOOT_COMPLETED is the first correct step in this.
You do it this way:
First, in AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
You create a service that extends GcmTaskService.
Here you make a public static method setupGcmTasks and you MUST #override onInitializeTasks. This callback is invoked when your app gets updated.
Key here is, that you set updateCurrent(true) for the task, so it replaces the existing one, making things much easier for you (rescheduling, etc).
public class MyTaskService extends GcmTaskService {
public static void setupGcmTasks(#NonNull Context context) {
GcmNetworkManager networkManager = GcmNetworkManager.getInstance(context);
Task task = new PeriodicTask.Builder()... // create your task
.setTag(YOUR_TASK_TAG)
.setUpdateCurrent(true)
.setPersisted(true)
.build();
networkManager.schedule(task);
}
#Override
public void onInitializeTasks() {
super.onInitializeTasks();
setupGcmTasks(getApplicationContext());
}
#Override
public int onRunTask(TaskParams taskParams) {
try {
switch (taskParams.getTag()) {
case YOUR_TASK_TAG:
// Do your stuff
break;
}
} catch (Exception e) {
// Log it
}
return GcmNetworkManager.RESULT_SUCCESS;
}
}
And finally, a BroadcastReceiver for device boots
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent != null && intent.getAction() != null &&
intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
myTaskService.setupGcmTasks(context); // Call the static of your service
}
}
}

android: scheduling job every hour forever

I have a web service on my server that needs to be pinged every hour. For this, I am using an Android app to ping it every hour. I have tried using Alarm manager but it stops working after few hours and if I swipe exit it. I have tried using service but for some reason, that doesn't seem to work and my app keeps crashing. I have am thinking about using Firebase Job dispatcher. My requirement is that the app needs to ping the web service on my server every hour. This should go on for at least next 3-4 months. Is there a way to accomplish this ? Thanks in advance!
EDIT: I have tried broadcast receiver with Alarm Manager but have not been able to sustain the firing for more then 4 hours.
I second Anantha's answer but seems like job parameters are little off for your needs.
You can go over this article to learn about the subtle differences between various Job schedulers.
As a matter of fact, even Google recommends using Firebase Job Schedular if the app needs to do a network communication due to various reasons. Please watch the attached video on the Github page for more info on the same. This also gives you basic code to kickstart your application. You can just change the job parameters to suit your needs
Hopefully, this below code should suit your requirement of triggering every one hour with a tolerance of 15 minutes
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(getContext()));
final int periodicity = (int)TimeUnit.HOURS.toSeconds(1); // Every 1 hour periodicity expressed as seconds
final int toleranceInterval = (int)TimeUnit.MINUTES.toSeconds(15); // a small(ish) window of time when triggering is OK
Job myJob = dispatcher.newJobBuilder()
// the JobService that will be called
.setService(yourJobService.class)
// uniquely identifies the job
.setTag("my-unique-tag")
// recurring job
.setRecurring(true)
// persist past a device reboot
.setLifetime(Lifetime.FOREVER)
// start between 0 and 60 seconds from now
.setTrigger(Trigger.executionWindow(periodicity, toleranceInterval))
// overwrite an existing job with the same tag
.setReplaceCurrent(true)
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
// constraints that need to be satisfied for the job to run
.setConstraints(
// only run on an unmetered network
Constraint.ON_ANY_NETWORK
)
.setExtras(schedulerextras)
.build();
dispatcher.mustSchedule(myJob);
Jhon you can use firebase jobdispatcher. because it will support from api level 9. you can see below how to create job dispatcher and how to call it.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scheduleJob(this);
}
public static void scheduleJob(Context context) {
//creating new firebase job dispatcher
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
//creating new job and adding it with dispatcher
Job job = createJob(dispatcher);
dispatcher.mustSchedule(job);
}
public static Job createJob(FirebaseJobDispatcher dispatcher){
Job job = dispatcher.newJobBuilder()
//persist the task across boots
.setLifetime(Lifetime.FOREVER)
//.setLifetime(Lifetime.UNTIL_NEXT_BOOT)
//call this service when the criteria are met.
.setService(ScheduledJobService.class)
//unique id of the task
.setTag("UniqueTagForYourJob")
//don't overwrite an existing job with the same tag
.setReplaceCurrent(false)
// We are mentioning that the job is periodic.
.setRecurring(true)
// Run between 30 - 60 seconds from now.
.setTrigger(Trigger.executionWindow(30, 60))
// retry with exponential backoff
.setRetryStrategy(RetryStrategy.DEFAULT_LINEAR)
//.setRetryStrategy(RetryStrategy.DEFAULT_EXPONENTIAL)
//Run this job only when the network is available.
.setConstraints(Constraint.ON_ANY_NETWORK, Constraint.DEVICE_CHARGING)
.build();
return job;
}
public static Job updateJob(FirebaseJobDispatcher dispatcher) {
Job newJob = dispatcher.newJobBuilder()
//update if any task with the given tag exists.
.setReplaceCurrent(true)
//Integrate the job you want to start.
.setService(ScheduledJobService.class)
.setTag("UniqueTagForYourJob")
// Run between 30 - 60 seconds from now.
.setTrigger(Trigger.executionWindow(30, 60))
.build();
return newJob;
}
public void cancelJob(Context context){
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
//Cancel all the jobs for this package
dispatcher.cancelAll();
// Cancel the job for this tag
dispatcher.cancel("UniqueTagForYourJob");
}}
ScheduledJobService.java
public class ScheduledJobService extends JobService {
private static final String TAG = ScheduledJobService.class.getSimpleName();
#Override
public boolean onStartJob(final JobParameters params) {
//Offloading work to a new thread.
new Thread(new Runnable() {
#Override
public void run() {
codeYouWantToRun(params);
}
}).start();
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
public void codeYouWantToRun(final JobParameters parameters) {
try {
Log.d(TAG, "completeJob: " + "jobStarted");
//This task takes 2 seconds to complete.
Thread.sleep(2000);
Log.d(TAG, "completeJob: " + "jobFinished");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//Tell the framework that the job has completed and doesnot needs to be reschedule
jobFinished(parameters, true);
}
}}
You will need to use JobScheduler(api >21 ) and GcmNetworkManager (api<21) depending on the api level of android. Check out this library from evernote which takes care of it.
Do you try broadcast receiver? I use Broadcast Receiver with Alarm Manager to vibrate every minute and it work fine. The only problem is that when device turn off or restarted, it not vibrate till I enter my application.
My test code.
public void setAlarm() {
alarmMgr =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(AlarmManagerActivity.this, AlarmManagerBroadcastReceiver.class);
intent.setAction("a.b.c.d");
PendingIntent pi = PendingIntent.getBroadcast( getApplicationContext(), 0, intent, 0);
//After after 5 seconds
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE, 40);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()
, (1000) * (60)
, pi);
}
My receiver
#Override
public void onReceive(Context context, Intent intent) {
Log.d(getClass().getSimpleName(), Intent.ACTION_BOOT_COMPLETED);
if ( intent.getAction().equals("a.b.c.d")) {
Log.d(getClass().getSimpleName(), "Custom Broadcast01");
Vibrator vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(10000);
}
else
Log.d(getClass().getSimpleName(), "no this action for intent!");
}
Broadcast receiver to start Alarm when device restart
<receiver
android:name=".OnBootBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class OnBootBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
setAlarm();
}
}

How to schedule a job using Jobscheduler

I am learning how to use JobScheduler. as shown in onresume method, I set the criteria to be met in order to execute the job, the
job will be scheduled when the device is not charging, no matter the device is idle or not and the job will be executed every
7 seconds.
at run time, the usb cable is connected to the device in order to install the App which means the device is charging, so after
installing the App the job have not started because the device is charging, but after i unplug the usb cable i exected the job
to be executed but what happened is that the job never started, and i could not understand why
please let me know why such behavior is happeneing and please let me know the answer of the following question it will help me to
better understand the jobScheduler:
Q: is setRequiresCharging(false) means, that the task will be executed only if the device is NOT charging or it means that
the task will be executed no matter if the device is charging or not?
main activity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static int jobId = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.w(TAG, "onCreate");
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
Log.w(TAG, "onResume");
ComponentName serviceComponent = new ComponentName(this, MyJobService.class);
JobInfo.Builder builder = new JobInfo.Builder(jobId, serviceComponent);
builder.setRequiresCharging(false);
builder.setRequiresDeviceIdle(false);
builder.setPeriodic(7 * 1000);
JobScheduler jobScheduler = (JobScheduler) getApplication().getSystemService(Context.JOB_SCHEDULER_SERVICE);
jobScheduler.schedule(builder.build());
}
}
jobService:
package example.com.jobscheduler_00;
public class MyJobService extends JobService {
private static final String TAG = MyJobService.class.getSimpleName();
#Override
public boolean onStartJob(JobParameters params) {
Log.w(TAG, "onStartJob JobId: " + params.getJobId());
Toast.makeText(this, "onStartJob JobId:" + params.getJobId(), Toast.LENGTH_SHORT).show();
jobFinished(params, false);
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.w(TAG, "onStopJob");
Toast.makeText(this, "onStopJob JobId:" + params.getJobId(), Toast.LENGTH_SHORT).show();
return true;
}
}
Is setRequiresCharging(false) means, that the task will be executed only if the device is NOT charging or it means that the task will be executed no matter if the device is charging or not?
From the documentation:
Specify that to run this job, the device needs to be plugged in. This defaults to false.
In other words, if you want your job to be run only in condition, when the device is charging - you should pass true. By default it is false, which means charging criteria is disregarded, i.e. your job will be executed regardless the device is charging or no (assuming other criterias are fulfilled).
You may check whether your job has started successfully by the int value that JobScheduler.schedule(JobInfo job) returns. It will return either RESULT_SUCCESS or RESULT_FAILURE.
The new WorkManager API will help you set necessary constraints for the task you want to schedule.
Have a look at this video for a brief intro - https://www.youtube.com/watch?v=pErTyQpA390 (WorkManager at 21:44).
EDIT: Adding an example to showcase the capabilities of the new API
For eg:
You can set constraints related to charging state of the device like this (along with other constraints like if the device is supposed to be idle for the task to run etc..)
// Create a Constraints that defines when the task should run
Constraints yourConstraints = new Constraints.Builder()
.setRequiresDeviceIdle(true/false)
.setRequiresCharging(true/false)
// Many other constraints are available
.build();
// ...then create a OneTimeWorkRequest that uses those constraints
OneTimeWorkRequest yourWork =
new OneTimeWorkRequest.Builder(YourWorkerClass.class)
.setConstraints(yourConstraints)
.build();

Android - Periodic Background Service - Advice

I am working on an app that will relay information about its location to a remote server. I am intending to do it by doing a simple HTTP post to the web-server and all is simple and fine.
But according to the spec, the app needs to execute itself from time to time, lets say once in every 30 mins. Be independent of the interface, meaning which it needs to run even if the app is closed.
I looked around and found out that Android Services is what needs to be used. What could I use to implement such a system. Will the service (or other mechanism) restart when the phone restarts?
Thanks in advance.
Create a Service to send your information to your server. Presumably, you've got that under control.
Your Service should be started by an alarm triggered by the AlarmManager, where you can specify an interval. Unless you have to report your data exactly every 30 minutes, you probably want the inexact alarm so you can save some battery life.
Finally, you can register your app to get the bootup broadcast by setting up a BroadcastReceiver like so:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
// Register your reporting alarms here.
}
}
}
You'll need to add the following permission to your AndroidManifest.xml for that to work. Don't forget to register your alarms when you run the app normally, or they'll only be registered when the device boots up.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Here is a semi-different way to keep the service going forever. There is ways to kill it in code if you'd wish
Background Service:
package com.ex.ample;
import android.app.Service;
import android.content.*;
import android.os.*;
import android.widget.Toast;
public class BackgroundService extends Service {
public Context context = this;
public Handler handler = null;
public static Runnable runnable = null;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "Service created!", Toast.LENGTH_LONG).show();
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(context, "Service is still running", Toast.LENGTH_LONG).show();
handler.postDelayed(runnable, 10000);
}
};
handler.postDelayed(runnable, 15000);
}
#Override
public void onDestroy() {
/* IF YOU WANT THIS SERVICE KILLED WITH THE APP THEN UNCOMMENT THE FOLLOWING LINE */
//handler.removeCallbacks(runnable);
Toast.makeText(this, "Service stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "Service started by user.", Toast.LENGTH_LONG).show();
}
}
Here is how you start it from your main activity or wherever you wish:
startService(new Intent(this, BackgroundService.class));
onDestroy() will get called when the application gets closed or killed but the runnable just starts it right back up.
I hope this helps someone out.
The reason why some people do this is because of corporate applications where in some instances the users/employees must not be able to stop certain things :)
http://i.imgur.com/1vCnYJW.png
EDIT
Since Android O (8.0) you have to use JobManager for scheduled tasks. There is a library called Android-Job by Evernote which will make periodic background work a breeze on all Android versions. I have also made a Xamarin Binding of this library.
Then all you need to do is the following:
In your application class:
public class MyApp extends Application {
#Override
public void onCreate() {
super.onCreate();
JobManager.create(this).addJobCreator(new MyJobCreator());
}
}
Create the following two classes YourJobCreator and YourSyncJob(Where all the work will be done. Android allocates time for all the background jobs to be run. For android versions < 8.0 it will still run with an Alarm manager and background service as per normal)
public class MyJobCreator implements JobCreator {
#Override
#Nullable
public Job create(#NonNull String tag) {
switch (tag) {
case MySyncJob.TAG:
return new MySyncJob();
default:
return null;
}
}
}
public class MySyncJob extends Job {
public static final String TAG = "my_job_tag";
#Override
#NonNull
protected Result onRunJob(Params params) {
//
// run your job here
//
//
return Result.SUCCESS;
}
public static void scheduleJob() {
new JobRequest.Builder(MySyncJob.TAG)
.setExecutionWindow(30_000L, 40_000L) //Every 30 seconds for 40 seconds
.build()
.schedule();
}
}
You should schedule your service with alarm manager, first create the pending intent of service:
Intent ii = new Intent(getApplicationContext(), MyService.class);
PendingIntent pii = PendingIntent.getService(getApplicationContext(), 2222, ii,
PendingIntent.FLAG_CANCEL_CURRENT);
Then schedule it using alarm manager:
//getting current time and add 5 seconds to it
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 5);
//registering our pending intent with alarmmanager
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), pi);
this will launch your service after 5 seconds of current time. You can make your alarm repeating.
You can use Alarm Manager to start Service at specified time and then repeat alarm in specified interval. When alarm goes on you can start service and connect to server and make what you want

Categories

Resources