【Android】android线程处理机制1
通过一个例子来理解android的线程处理机制,对于在这里用runnable接口的效果。
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class Handler2 extends Activity {
/** Called when the activity is first created. */
public Button startbutton;
public Button endbutton;
public ProgressBar bar;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bar=(ProgressBar)findViewById(R.id.bar);
startbutton=(Button)findViewById(R.id.startbutton);
startbutton.setOnClickListener(new startbuttonListener());
endbutton=(Button)findViewById(R.id.endbuton);
// endbutton.setOnClickListener(new endbuttonListener());
}
class startbuttonListener implements OnClickListener
{
public void onClick(View v)
{
bar.setVisibility(View.VISIBLE);
handler.post(updateThread);
}
}
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
//super.handleMessage(msg);
bar.setProgress(msg.arg1);
System.out.println("msg "+msg.arg1);
handler.post(updateThread);
}
};
Runnable updateThread=new Runnable(){
int i=0;
public void run()
{
i=i+10;
Message msg=handler.obtainMessage();
msg.arg1=i;
System.out.println("updateProgress "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.sendMessage(msg);
if(i==100)
{
handler.removeCallbacks(updateThread);
}
}
};
转载自百度空间zhao_xu_dong的分享,原文地址为:http://apps.hi.baidu.com/share/detail/31068106。
感谢原文作者的无私分享。