Reputation: 658
I want to update the data from server for every 15 min using time scheduling. Is there a way, so we can update the data background?
Upvotes: 2
Views: 1075
Reputation: 11844
Use the alarm manager set it to send a broadcast to wake up your intentservice instance every 15 mins and do the update from there.
Edit:
I added the boot complete way of doing it for your convenience, you might want to start the alarm thing upon opening your app. Either way just follow the codes where alarm manager and intent service are.
First off create a broadcast receiver that listens for the boot complete
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.CheckUpdateIntentService;
public class BootCompleteReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//Create pending intent to trigger when alarm goes off
Intent i = new Intent(context, CheckUpdateIntentService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
//Set an alarm to trigger the pending intent in intervals of 15 minutes
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//Trigger the alarm starting 1 second from now
long triggerAtMillis = Calendar.getInstance().getTimeInMillis() + 1000;
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
}
Now for the intent service to do the actual updates
import android.content.Context;
import android.content.Intent;
import android.app.IntentService;
public class CheckUpdateIntentService extends IntentService {
public CheckUpdateIntentService()
{
super(CheckUpdateIntentService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent)
{
//Actual update logic goes here
//Intent service itself is already a also a Context so you can get the context from this class itself
Context context = CheckUpdateIntentService.this;
//After updates are done the intent service will shutdown itself and wait for the next interval to run again
}
}
In your AndroidManifest.xml add the following items:
Permission to receive the boot complete broadcast
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Then in the application tags add the BootCompleteReceiver you have created with the corresponding intent filter you are interested in, and of course the intentservice component
<receiver android:name=".BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".CheckUpdateIntentService" ></service>
This is a very skeletal implementation, you can try it out first if you need more help, let us know.
Upvotes: 1