Android更新UI的两种方法(一)

Android更新UI的两种方法(一)

在Android开发中,通常将联网、i/o、复杂的算法、查询数据库(大量数据)等耗时操作放在子线程中进行,这样可以避免ANR常(application not responing)。在子线程的操作过程中常常需要更新UI,而更新UI操作主要有两种方法。一种是直接在子线程中覆盖runOnUiThread()方法,另一种则是使用Android的消息机制。
本文先介绍第一种方法:
界面如图所示:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    private TextView textView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.bt_button);
        textView = (TextView) findViewById(R.id.tv_message);
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_button:
                new workThread().start();
                break;
            default:
                break;
        }
    }

    private class workThread extends Thread{
	//servlet地址
        final String serverPath="http://xxx.xxx.xxx.xxx:8080/ServletTest/MainMessage";
        @Override
        public void run() {
            super.run();
            try {
                URL url=new URL(serverPath);
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                httpURLConnection.setConnectTimeout(5000);
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.setRequestProperty("contentType","utf-8");
                final int responseCode=httpURLConnection.getResponseCode();
                if (responseCode==200){//200==OK
                    InputStream inputStream=httpURLConnection.getInputStream();
                    BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream,"GB2312"));//设置编码格式
                    final String responseMsg=bufferedReader.readLine();
                    runOnUiThread(new Runnable() {//使用runOnUIThread()方法更新主线程
                        @Override
                        public void run() {
                            textView.setText(responseMsg);
                        }
                    });
                    bufferedReader.close();
                    httpURLConnection.disconnect();
                }else {
                    Toast.makeText(MainActivity.this,"responseCode="+responseCode,Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
点击按钮执行更新操作后界面如图所示:

猜你喜欢

转载自blog.csdn.net/sconghw/article/details/79106755