Android Background Download Data
I want to make a background running service (independent of an app) which would download weather data from server periodically every day. I already have code to download data from
Solution 1:
You can Create a Android Intent Service :-
publicclassBackendServiceextendsIntentService {
publicBackendService() {
super("BackendService");
}
@OverrideprotectedvoidonHandleIntent(Intent intent) {
// Your Download code
}
}
Then set a Alarm Receiver to set the interval in which service will be called.
publicvoidbackendscheduleAlarm() {
// Construct an intent that will execute the AlarmReceiverIntentintent=newIntent(getApplicationContext(), BackendAlarm.class);
// Create a PendingIntent to be triggered when the alarm goes offfinalPendingIntentpIntent= PendingIntent.getBroadcast(this, BackendAlarm.REQUEST_CODE,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every 1 hourlongfirstMillis= System.currentTimeMillis(); // first run of alarm is immediateintintervalMillis=3000; //3600000; // 60 minAlarmManagerbackendalarm= (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
backendalarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis, intervalMillis, pIntent);
}
And Create a Broadcast Receiver class to call that service:
publicclassBackendAlarmextendsBroadcastReceiver {
publicstaticfinalintREQUEST_CODE=12345;
// Triggered by the Alarm periodically (starts the service to run task)@OverridepublicvoidonReceive(Context context, Intent intent) {
Intenti=newIntent(context, BackendService.class);
i.putExtra("foo", "bar");
context.startService(i);
} }
Solution 2:
read about Android Services which are mainly made for such background work:
http://developer.android.com/guide/components/services.html
all you need is to start the service on a certain time you set.
Post a Comment for "Android Background Download Data"