安卓:执行code在定期 [英] Android: execute code in regular intervals

查看:136
本文介绍了安卓:执行code在定期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一些code在定期(连接到服务器,并从MySQL数据库中提取数据每分钟)。为此,我有一个同步类:

I need to perform some code in regular intervals (connect to a server and pull data from MySQL database every minute). For this purpose I have a Sync class:

public class Sync {

    static private Handler handler = new Handler();
    Runnable task;

    public Sync(Runnable task, long time) {
        this.task = task;
        handler.removeCallbacks(task);
        handler.postDelayed(task, time);
    }
}

和我的活动我有:

public void onCreate(Bundle savedInstanceState) {
    ...
    Sync sync = new Sync(call,60*1000);
    ...
}

final private Runnable call = new Runnable() {
    public void run() {
    //This is where my sync code will be, but for testing purposes I only have a Log statement
    Log.v("test","this will run every minute");
    }
};

我曾试图与更短的时间来进行测试,但它只能运行一次。当它记录的消息首次,它也是最后一次。有谁看到什么Im做erong在这里?谢谢!

I have tried this with a shorter time period for testing, but It only runs once. When it Logs the message for the first time, its also the last. Does anyone see what Im doing erong here? Thanks!

推荐答案

您可以做到这一点使用下面的code, 希望它可以帮助!

You can do that using the below code, Hope it helps!

final Handler handler = new Handler(); 
Runnable runnable = new Runnable() { 

    @Override 
    public void run() { 
        try{
            //do your code here
            //also call the same runnable 
            handler.postDelayed(this, 1000);
        }
        catch (Exception e) {
            // TODO: handle exception
        }
        finally{
            //also call the same runnable 
            handler.postDelayed(this, 1000); 
        }
    } 
}; 
handler.postDelayed(runnable, 1000); 

这篇关于安卓:执行code在定期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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