Handler的第一种用法Handler.post()
public class MainActivity extends AppCompatActivity {
private TextView mTv;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv = (TextView) findViewById(R.id.tv);
new Thread() {
@Override
public void run() {
//实现业务逻辑
handler.post(new Runnable() {
@Override
public void run() {
//更新UI
mTv.setText("Handler的第一种用法");
}
});
super.run();
}
}.start();
}
}
Handler的第二种用法Handler内部类实现Runnable接口
public class MainActivity extends AppCompatActivity {
private TextView mTv;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv = (TextView) findViewById(R.id.tv);
final MyRunnable myRunnable = new MyRunnable();
new Thread() {
@Override
public void run() {
handler.post(myRunnable);
super.run();
}
}.start();
}
public class MyRunnable implements Runnable {
@Override
public void run() {
mTv.setText("Handler的第二种使用方法");
}
}
}
Handler的第三种使用方法handlerMessage()方式
public class MainActivity extends AppCompatActivity {
private TextView mTv;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
mTv.setText("Handler的第三种基本使用方式");
break;
}
super.handleMessage(msg);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTv = (TextView) findViewById(R.id.tv);
new Thread() {
@Override
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
super.run();
}
}.start();
}
}