Android Download Data for Android

I want to make a background launch of the service (regardless of the application), which will periodically download weather data from the server every day. I already have code to download data from the server and save it to the database.

What I would like to know is the best way to run the service periodically.

+2
android
source share
2 answers

You can create an Android Intent service: -

public class BackendService extends IntentService { public BackendService() { super("BackendService"); } @Override protected void onHandleIntent(Intent intent) { // Your Download code } } 

Then install the emergency receiver to set the interval at which the service will be called.

 public void backendscheduleAlarm() { // Construct an intent that will execute the AlarmReceiver Intent intent = new Intent(getApplicationContext(), BackendAlarm.class); // Create a PendingIntent to be triggered when the alarm goes off final PendingIntent pIntent = PendingIntent.getBroadcast(this, BackendAlarm.REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT); // Setup periodic alarm every 1 hour long firstMillis = System.currentTimeMillis(); // first run of alarm is immediate int intervalMillis = 3000; //3600000; // 60 min AlarmManager backendalarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE); backendalarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, intervalMillis, pIntent); } 

And create a Broadcast Receiver class to call this service:

 public class BackendAlarm extends BroadcastReceiver { public static final int REQUEST_CODE = 12345; // Triggered by the Alarm periodically (starts the service to run task) @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(context, BackendService.class); i.putExtra("foo", "bar"); context.startService(i); } } 
+2
source share

Read about Android services that are primarily designed for these background jobs:

http://developer.android.com/guide/components/services.html

all you need to do is start the service at a specific time.

0
source share

All Articles