Android的后台下载数据 [英] Android Background download data

查看:146
本文介绍了Android的后台下载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打一个后台运行的服务(独立于应用程序),它会从服务器周期性每天下载天气数据。我已经有code键从服务器下载的数据,并将其存储在数据库中。

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 the server and store it in the database.

我想知道的是,什么是定期运行该服务的最佳方式。

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

推荐答案

您可以创建一个Android的意图服务: -

You can Create a Android Intent Service :-

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

然后设置一个报警接收机设置在服务将被调用的时间间隔。

Then set a Alarm Receiver to set the interval in which 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 that 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);
} }

这篇关于Android的后台下载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆