Reputation: 63
I need to execute web service every Hour in the background
Every hour, will check if Internet is available then execute a web service and update data.
How can I do this?
My background service
public class MyService extends Service {
String tag="TestService";
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
}
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
if(isInternet)
{
AsyTask web= new AsyTask();
web.execute();
}
Log.i(tag, "Service started...");
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
Upvotes: 4
Views: 4088
Reputation: 8023
The idea would be to use the AlarmManager to start a background service every hour.
Setup Alarm Manager to start a background service every 60 minutes. This can be done in any of the activities.
startServiceIntent = new Intent(context,
WebService.class);
startWebServicePendingIntent = PendingIntent.getService(context, 0,
startServiceIntent, 0);
alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(), 60*1000*60,
startWebServicePendingIntent);
Create a class WebService
which extends Service
then add the method to sync data with the server inside the onStartCommand()
method of the Service. Also, do not forget to declare the service in the manifest.
Edit 1 :
public class WebService extends Service {
String tag="TestService";
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStart(intent, startId);
if(isInternet)
{
AsyTask web= new AsyTask();
web.execute();
}
Log.i(tag, "Service started...");
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
Upvotes: 3
Reputation: 1141
add you code of calling webservice inside run method of timer task just like below
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
if(isInternet)
{
AsyTask web= new AsyTask();
web.execute();
}
Log.i(tag, "Service started...");
}
}, 0, 3600000);
Upvotes: 0