android开发积累3-android多线程操作
在android进行多线程操作,可以使用android.os.HandlerThread,android.os.Handler类来进行。
下面的例子是,界面上一个TextView控件,使用一个新线程在这个TextView上面显示数字,每隔1秒加1,按button后,停止更新计数。
?
package Test.wangfu;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestActivity extends Activity {
??? /** Called when the activity is first created. */
??? private boolean isRuning=true;
??? private int timer=0;
??? private Handler hander;
??? private HandlerThread thread;
??? private TextView text;
??? @Override
??? public void onCreate(Bundle savedInstanceState) {
??? ??? super.onCreate(savedInstanceState);?
??? ??? this.setContentView(R.layout.main);
??? ??? final Button button = (Button) this.findViewById(R.id.callButton);
??? ??? text = (TextView) this.findViewById(R.id.textLabel);
??? ??? class mylistener implements OnClickListener {
??? ??? ??? public void onClick(View v) {
??? ??? ??? ??? isRuning=false;
??? ??? ??? ??? text.setText("结束");
??? ??? ??? }
??? ??? }
??? ??? button.setOnClickListener(new mylistener());
??? ???
??? ??? //多线程
??? ??? thread=new HandlerThread("mytestthread");
??? ??? thread.start();
??? ??? hander=new Handler(thread.getLooper());
??? ???
??? ??? Runnable r=new Runnable(){
??? ??? ??? public void run() {
??? ??? ??? ??? // TODO Auto-generated method stub
??? ??? ??? ??? if(isRuning){
??????????????????? //使用runOnUiThread更新控件值,不使用的话将会出现:Only the original thread that created a //view hierarchy can touch its views.的错误。
??? ??? ??? ??? ??? TestActivity.this.runOnUiThread(new Runnable(){
??? ??? ??? ??? ??? ??? public void run() {
??? ??? ??? ??? ??? ??? ??? // TODO Auto-generated method stub
??? ??? ??? ??? ??? ??? ??? text.setText(String.valueOf(timer));
??? ??? ??? ??? ??? ??? }});
??? ??? ??? ??? ??? timer++;
??? ??? ??? ??????? hander.postDelayed(this, 1000);??? ???
??? ??? ??? ??? }
??? ??? ??? }
??? ??? };
??? ??? hander.postDelayed(r, 1000);???
??? }
}
?
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
??? android:layout_width="fill_parent"
??? android:layout_height="fill_parent"
??? android:orientation="vertical" >
??? <TextView
??????? android:id="@+id/textLabel"
??????? android:layout_width="fill_parent"
??????? android:layout_height="wrap_content"
??????? android:text="Enter Number to Dial:" />
??? <Button
??????? android:id="@+id/callButton"
??????? android:layout_width="159dp"
??????? android:layout_height="wrap_content"
??????? android:text="停止" />
</LinearLayout>
?
?
