android - 我想通过给定时间限制来更新来自服务器的数据

标签 android database

我想使用时间安排每 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/

相关文章:

java - 仅当在 fragment 中单击菜单项时,如何使 gridview 中的复选框可见?

java - aSyncTask 死锁第二个 aSyncTask

java - 在android中设置proguard规则,它可以只加密代码吗?

android - 导入 OpenIntents 以在 Android 应用程序中使用 OI 文件管理器

database - 可以使用哈希算法来节省数据库空间吗?

java - 在我的应用程序中,我需要记录每个来电和去电

php - 更多的 MySql 表会减慢对 MySql 数据库的搜索吗?

MySQL 5.5 响应时间慢

php - SQL数据库同步

用于标记多行而不是一行的 SQL Server 查询