一丶在子线程中不允许更改主线程中的控件的信息,也不允许在子线程中用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) ;
}
}
本文出自 “android笔记” 博客,请务必保留此出处http://2585211.blog.51cto.com/10044233/1669879
原文地址:http://2585211.blog.51cto.com/10044233/1669879