android UI跨線程操做

 android應用程序也是單線程程序,主線程爲UI線程。android

 android 線程是非安全的,即不要在子線程中更新 UI。安全

  • public class MasterActivity extends Activity {  
  •     TextView tv = null;  
  •     Button btn = null;  
  •       
  •     Handler mHandler = new Handler() {  
  •         @Override  
  •         public void handleMessage(Message msg) {  
  •             if(msg.what == 1) {  
  •                 tv.setText("update UI is success!");  
  •                 btn.setText("update UI is success!");  
  •             }  
  •             super.handleMessage(msg);  
  •         }  
  •     };  
  •       
  •     @Override  
  •     public void onCreate(Bundle savedInstanceState) {  
  •         super.onCreate(savedInstanceState);  
  •         setContentView(R.layout.main);  
  •         System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().getId());  
  •         tv = (TextView)findViewById(R.id.text);  
  •         btn = (Button)findViewById(R.id.btn);  
  •         btn.setOnClickListener(new OnClickListener() {  
  •               
  •             @Override  
  •             public void onClick(View v) {  
  •                 Thread thread = new Thread(new Runnable() {  
  •                       
  •                     @Override  
  •                     public void run() {  
  •                         System.out.println(Thread.currentThread().getName() + ": " + Thread.currentThread().getId());  
  •                         Message msg = mHandler.obtainMessage();  
  •                         msg.what = 1;  
  •                         msg.sendToTarget();  
  •                     }});  
  •                 thread.start();  
  •             }  
  •         });  
相關文章
相關標籤/搜索