Only the original thread that created a view hierarchy can touch its views.

//Only the original thread that created a view hierarchy can touch its views.
//不能在非UI线程里更新UI



public class MainActivity extends AppCompatActivity {

    private Handler handler;

    @BindView(R.id.get_btn)
    Button get_btn;

    @BindView(R.id.post_btn)
    Button post_btn;

    @BindView(R.id.result_view)
    TextView result_view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //主线程的handler
        handler = new Handler();

    }
    @OnClick(R.id.get_btn)
    public void getMsg(){
        doGet();
    }
    @OnClick(R.id.post_btn)
    public void postMsg(){



    }

    public void doGet(){
        //创建okhttpClient对象
        OkHttpClient okhttpClient = new OkHttpClient();
        //构建Request
        Request.Builder builder = new Request.Builder();
        Request request = builder.get().url("https://www.baidu.com").build();
        //将Request封装为Call
        Call call = okhttpClient.newCall(request);
        //执行Call
        //异步执行   提供回调接口
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Toast.makeText(MainActivity.this, "网络不给力", Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                // Only the original thread that created a view hierarchy can touch its views.
                //result_view.setText(string);
                new Thread(){
                    @Override
                    public void run() {
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                result_view.setText(string);
                            }
                        });
                    }
                }.start();

            }
        });
    }
}

猜你喜欢

转载自majunminq.iteye.com/blog/2367474