Reputation: 332
Here's the situation.
I have an app with a database. The db must update every X minutes. The data is on a web server. The communication with the server will take about 10 httpget requests. So far accomplished a background service and a HTTPget function for getting the new information and updating the db. The problem is that it must update in background at that X minutes. I'm unsure what and how to realize that.
1.Use a delay function and run it at every X minutes ? 2.Use a sleep thread and wake it up at every X minutes ?
Or something else ?
Upvotes: 0
Views: 145
Reputation: 4659
Use Intent Service and run it periodically every X minutes using alarm manager.
Use a Broadcast Receiver to trigger the intent service , so that the service continues to run even when user switches on their phone
Step 1. Create your Intent Service
public class SimpleIntentService extends IntentService {
public SimpleIntentService() {
super("SimpleIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO your task
}
}
Step 2. Repeating pending intent for service using AlarmManager
Intent myIntent = new Intent(context, StartMyServiceReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, myIntent, 0);
alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES, pi);
Step 3. In order to ensure that your service runs even after switch off when phone boots up again , create an PowerEventReceiver
public class PowerEventReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
//start your service
}
}
}
P.S: Remember to register your service and receivers in In AndroidManifest.
Upvotes: 1
Reputation: 1255
use alarm manager to trigger the event after some time, in your case you have to start sending request to server after every x minutes.. refer here http://www.learn-android-easily.com/2013/06/scheduling-task-using-alarm-manager.html
Upvotes: 1