public class MainActivity extends Activity implements OnClickListener
{
TextView textView = null;
private View mProgress;
private Handler mHandler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
textView = (TextView) findViewById(R.id.textView1);
mProgress = findViewById(R.id.progressBar1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.button1:
btn1Click();
break;
default:
break;
}
}
private void btn1Click()
{
mProgress.setVisibility(View.VISIBLE);
new Thread()
{
@Override
public void run()
{
final String str = update();
Runnable action = new Runnable()//该方法仍然是在main线程中完成的
{
@Override
public void run()//run里进行main线程的事件
{
textView.setText(str);
mProgress.setVisibility(View.GONE);
Log.e("runnable", Thread.currentThread().getName());
}
};
/*
* 除Handler外的其他三种方法,适用于控件较少的场景
*/
runOnUiThread(action);//方法一
textView.post(action);//方法二,post方法执行前会调用
mHandler.post(action);//方法三
mHandler.postDelayed(action, 3000);//方法三可以加个延时
}
}.start();
}
private String update()
{
return "更新完成!";
}
}
注:
1.handler.post这个函数的作用是把Runnable里面的run方法里面的这段代码发送到消息队列中,等待运行。
如果handler是以UI线程消息队列为参数构造的,那么是把run里面的代码发送到UI线程中,等待UI线程运行这段代码。
如果handler是以子线程线程消息队列为参数构造的,那么是把run里面的代码发送到子线程中,等待子线程运行这段代码。
转载于:https://blog.51cto.com/glblong/1206265