我想制作一个后台运行服务(独立于应用程序),它会每天定期从服务器下载天气数据。我已经有了从服务器下载数据并将其存储在数据库中的代码。
我想知道的是,定期运行服务的最佳方式是什么。
答案 0 :(得分:2)
您可以创建Android Intent服务: -
public class BackendService extends IntentService {
public BackendService() {
super("BackendService");
}
@Override
protected void onHandleIntent(Intent intent) {
// Your Download code
}
}
然后设置一个Alarm Receiver来设置调用服务的时间间隔。
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);
}
创建一个广播接收器类来调用该服务:
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);
} }
答案 1 :(得分:0)
阅读主要针对此类背景工作的Android服务:
http://developer.android.com/guide/components/services.html
您只需在设定的某个时间启动服务即可。