android中的线程可以分为两种:MainThread(主线程也叫UI线程)与UI相关的线程都是运行在主线程中与WorkerThread(),原则上是不可以操作UI的
在一个应用程序当中,主线程通常用于接收用户的输入,以及将运算的结果反馈给用户
所以必须将一些可能产生阻塞的操作,必须放在worker Thread中
MainActivity.java
1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.view.View; 4 import android.view.View.OnClickListener; 5 import android.widget.Button; 6 import android.widget.ProgressBar; 7 import android.widget.TextView; 8 9 public class MainActivity extends Activity { 10 private TextView textview; 11 private Button button; 12 private ProgressBar progressbar; 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 textview = (TextView) findViewById(R.id.textview); 17 progressbar = (ProgressBar) findViewById(R.id.progressbar); 18 button = (Button) findViewById(R.id.button); 19 button.setOnClickListener(new ButtonListener()); 20 } 21 22 class ButtonListener implements OnClickListener{ 23 public void onClick(View v) { 24 Thread thread = new MyThread(); 25 thread.start(); 26 } 27 28 } 29 //worker Thread 30 class MyThread extends Thread{ 31 public void run(){ 32 for (int i = 0; i <= 100; i++) { 33 try { 34 Thread.sleep(1*100); 35 } catch (InterruptedException e) { 36 e.printStackTrace(); 37 } 38 progressbar.setProgress(progressbar.getProgress()+1);//在workerThread中是不可以修改UI的 progressbar列外 39 } 40 41 /* 42 try { 43 Thread.sleep(1*1000); 44 } catch (InterruptedException e) { 45 e.printStackTrace(); 46 } 47 //worker Thread是不允许操作IU的,程序运行会出错,(但是ProgressBar比较列外) 48 //textview.setText("来自于线程的修改");//workerThreal线程修改了TestView,会出错 49 */ 50 } 51 } 52 53 }
activity_main.xml
1 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 xmlns:tools="http://schemas.android.com/tools" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent" 5 android:paddingBottom="@dimen/activity_vertical_margin" 6 android:paddingLeft="@dimen/activity_horizontal_margin" 7 android:paddingRight="@dimen/activity_horizontal_margin" 8 android:paddingTop="@dimen/activity_vertical_margin" 9 tools:context=".MainActivity" > 10 11 <TextView 12 android:id="@+id/textview" 13 android:layout_width="wrap_content" 14 android:layout_height="wrap_content" 15 android:text="@string/hello_world" 16 />" 17 18 <ProgressBar 19 android:id="@+id/progressbar" 20 android:layout_width="match_parent" 21 android:layout_height="wrap_content" 22 style="?android:attr/progressBarStyleHorizontal" 23 android:layout_below="@id/textview" 24 />" 25 26 <Button 27 android:id="@+id/button" 28 android:layout_width="wrap_content" 29 android:layout_height="wrap_content" 30 android:layout_below="@id/progressbar" 31 android:text="启动线程" 32 /> 33 34 </RelativeLayout>