安卓开发定时刷新界面

Android客户端软件需要刷新某一部分界面,比如软件的升级和软件内部的更新。现在介绍Android里可以选用两种方式来实现此功能。

方式一、使用Timer(定时器)和TimerTask实现

示例代码:

public class MainActivity extends Activity {
    private TextView msg;

    final Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case 1:
                update();
                break;
            }
            super.handleMessage(msg);
        }
        void update() {
            //刷新msg的内容
        }
    };
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
        public void run() {
            Message message = new Message();
            message.what = 1;
            handler.sendMessage(message);
        }
    };
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        msg = (TextView) findViewById(R.id.txtMsg);
        msg.setText("你好啊!");
        timer.schedule(task, 1000 * 40, 1000 * 30); //启动timer
    }
    @Override
    protected void onDestroy() {
        if (timer != null) {// 停止timer
            timer.cancel();
            timer = null;
        }
        super.onDestroy();
    }
}


方式二、使用Runnable和Handler

示例代码

public class MainActivity extends Activity {
    private TextView msg;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        public void run() {
            this.update();
            handler.postDelayed(this, 1000 * 120);// 间隔120秒
        }
        void update() {
            //刷新msg的内容
        }
    }; 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        msg = (TextView) findViewById(R.id.txtMsg);
        msg.setText("你好啊!");
        handler.postDelayed(runnable, 1000 * 60);
    }
    @Override
    protected void onDestroy() {
        handler.removeCallbacks(runnable); //停止刷新
        super.onDestroy();
    }
}


第一种方式还适用于消息通知的方式实现更新,第二种方式通常是主动去检查是否需要刷新。对于定时刷新这种使用第二种方式更好

你可能感兴趣的:(Android)