Handler常见两种用法
1.Handler在Android的两个功能
1.1表示未来某时做某事
1.2线程间通信
2.演示源码如下:
package com.example.datastrorage;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class HandlerActivity extends AppCompatActivity {
private Handler mHandler=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler);
//延迟功能
// mHandler.postDelayed(new Runnable() {
// @Override
// public void run() {
// Toast.makeText(HandlerActivity.this, "我是handler!", Toast.LENGTH_SHORT).show();
// }
// },3000);
mHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
case 1:
Toast.makeText(HandlerActivity.this, "线程间通信成功", Toast.LENGTH_SHORT).show();
break;
}
}
};
new Thread(){
@Override
public void run() {
super.run();
Message msg=new Message();
msg.what=1;
mHandler.sendMessage(msg);
}
}.start();
}
}