我想使用时间安排每 15 分钟从服务器更新一次数据。有没有办法,让我们可以更新数据背景?
最佳答案
使用警报管理器将其设置为每 15 分钟发送一次广播以唤醒您的 intentservice 实例并从那里进行更新。
编辑:
为了您的方便,我添加了启动完整的方式,您可能希望在打开您的应用程序时启动闹钟。无论哪种方式,只需遵循警报管理器和 Intent 服务所在的代码即可。
首先创建一个监听启动完成的广播接收器
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.CheckUpdateIntentService;
public class BootCompleteReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
//Create pending intent to trigger when alarm goes off
Intent i = new Intent(context, CheckUpdateIntentService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
//Set an alarm to trigger the pending intent in intervals of 15 minutes
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//Trigger the alarm starting 1 second from now
long triggerAtMillis = Calendar.getInstance().getTimeInMillis() + 1000;
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, triggerAtMillis, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIntent);
}
}
现在让 Intent 服务进行实际更新
import android.content.Context;
import android.content.Intent;
import android.app.IntentService;
public class CheckUpdateIntentService extends IntentService {
public CheckUpdateIntentService()
{
super(CheckUpdateIntentService.class.getName());
}
@Override
protected void onHandleIntent(Intent intent)
{
//Actual update logic goes here
//Intent service itself is already a also a Context so you can get the context from this class itself
Context context = CheckUpdateIntentService.this;
//After updates are done the intent service will shutdown itself and wait for the next interval to run again
}
}
在您的 AndroidManifest.xml 中添加以下项目:
接收开机完成广播权限
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
然后在application标签中添加你创建的BootCompleteReceiver和你感兴趣的相应的intent filter,当然还有intentservice组件
<receiver android:name=".BootCompleteReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".CheckUpdateIntentService" ></service>
这是一个非常简单的实现,如果您需要更多帮助,您可以先尝试一下,让我们知道。
关于android - 我想通过给定时间限制来更新来自服务器的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13300555/