【问题标题】:Update data in background在后台更新数据
【发布时间】:2014-09-29 07:26:13
【问题描述】:
在我的应用程序中,我需要从服务器定期更新联系人列表、组列表和文件夹列表。我现在正在将它们保存到保存首选项中。目前我已经实现了一个方法,如果我有我需要的每种类型的列表,我会跳过登录时的更新并调用后台 asyncTask 在登录后更新此数据。问题是用户可以登录的连接很低,但他们无能为力,等待后台更新阻止其他 http 请求。
如何定期刷新这些数据?就像即使应用程序未处于活动状态也会更新数据的服务。
【问题讨论】:
标签:
android
performance
service
android-asynctask
【解决方案1】:
您可能应该使用Service。
Android Service Tutorial
manifest.xml
<service
android:name="MyService"
android:icon="@drawable/icon"
android:label="@string/service_name">
</service>
MyService.java
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
启动服务
// use this to start and trigger a service
Intent i= new Intent(context, MyService.class);
// potentially add data to the intent
i.putExtra("KEY1", "Value to be used by the service");
context.startService(i);