1.因为费时操作要放子线程,更新UI要放UI线程(主线程),所以子线程和主线程通信,通信的话要用到handler这个东西。

这里讲的比较简单,举2个例子说明

2.使用post的是handler ,使用message的是handler2

public class MainActivity extends AppCompatActivity {

private TextView textView;
private Handler handler = new Handler();

private Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case 1:
textView.setText(msg.obj.toString());
}
}
};

Button button;
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView =findViewById(R.id.textview);

new Thread(){
@Override
public void run() {
Message message = new Message();
//区分标志
message.what=1;
//传参到ui线程
message.obj=123123;
handler2.sendMessage(message);
}
}.start();


new Thread(){
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
textView.setText("fjidfjiijisdf");
}
});
}
}.start();
}


}

3. 实例化handler在其他线程的时候要下面这样写

 private Handler handler = new Handler(Looper.getMainLooper());

 

评论关闭
IT源码网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!