美文网首页
非主线程更新UI:Handler.post*方法

非主线程更新UI:Handler.post*方法

作者: 万杰高科 | 来源:发表于2017-08-13 22:18 被阅读0次

    学习心得

    • post*方法中的Runnable参数中的run代码会在主线程中执行
    • 总结非主线程更新UI的4非方法:Handler传递Message消息、调用Activity的runOnUIThread方法、通过handler.post*方法、AsynTask方法

    代码样例

    /**
     * Created by Rambo
     */
    
    public class MyActivity extends MainActivity {
    
        private EditText myEditText = null;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_my);
            myEditText = (EditText) findViewById(R.id.myEditText);
            final Handler myHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                }
            };
            new Thread(new Runnable() {
                @Override
                public void run() {
    
                    myHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            for (int i=0; i<5; i++){
                                try {
                                    Log.v(TAG, "main Thread:" + Thread.currentThread().getName());
                                    Thread.sleep(500);
                                    myEditText.setText(Thread.currentThread().getName() + ":" + i);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }, 1000);
                    for (int j=0; j<5; j++){
                        try {
                            Thread.sleep(500);
                            Log.v(TAG, "New Thread:" + Thread.currentThread().getName());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
    
                }
            }).start();
        }
    
    }
    

    相关文章

      网友评论

          本文标题:非主线程更新UI:Handler.post*方法

          本文链接:https://www.haomeiwen.com/subject/rexyrxtx.html