Android基础知识

Handler两种使用方法

2017-09-20  本文已影响0人  Mayo酱

post

public class PostActivity extends Activity {

    private Handler mHandler = new Handler();

    class DownloadThread extends Thread{

        @Override
        public void run() {
            super.run();
            try{
                Thread.sleep(5000);
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        //更新UI
                    }
                };
                mHandler.post(runnable);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

sendMessage

public class SendMessage extends Activity {

    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    //更新UI
                    break;
            }
        }
    };

    class DownloadThread extends Thread{
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
                Message msg = new Message();
//                Message msg = Message.obtain();  可以避免重复创建消息对象
//                Message msg = mHandler.obtainMessage(); 可以避免重复创建消息对象
//message有what,arg1/arg2(政协数据),obj
                msg.what = 1;
                mHandler.sendMessage(msg);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读