一丶在子線程中不允許更改主線程中的控件的資訊,也不允許在子線程中用toast,我們要更改的話
(1)消息機制:使用handler
(由主線程調用)
在主程式中Handler handler = new Handler(){
public void handleMessage(Message msg){
int type = msg.what ;//拿到msg的類型,再判斷
switch (type) {
case SUCCESS:
//拿到資訊
String info = (String)msg.obj ;
//
break;
case FAILED:
//拿到資訊
String faild = (String)msg.obj ;
Toast.makeText(MainActivity.this, faild, 0).show() ;
break;
case ERROR:
//拿到資訊
String error = (String)msg.obj ;
Toast.makeText(MainActivity.this, error, 0).show() ;
break;
}
};
};
而在子線程中要設定Message msg;
msg.what(設定類型)
msg.obj(設定内容)然後發送:handler.sendMessage(msg);
(2)常見消息處理api:
runOnUiThread(runnable): 在ui主線程中運作
playAtTime() : 在某個時間運作
playDelay(): 延時運作
例:public class MainActivity extends Activity {
private TextView tvinfo ;
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
System.out.println("接收到了消息");
tvinfo.setText((String)msg.obj) ;
};
} ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvinfo = (TextView) findViewById(R.id.tvinfo) ;
}
public void click(View view){
handler.postDelayed(new Runnable() {
@Override
public void run() {
Message msg = Message.obtain() ;
msg.obj = "哈哈哈,我改變了UI上的内容" ;
handler.sendMessage(msg) ;
}
}, 3000) ;
}
}