Handler
发送message:在工作线程给主线程发送消息
- sendMessage(Message message)
- sendEmptyMessage(int what)
处理Message:在主线程执行时,方法会被回调,建立通信基础
- handleMessage(Message msg)
使用它来发送message和处理message
Message
工作线程与主线程的发送的消息
Message通过属性what arg1 arg2传递整型数据
setData(Bundle bundle)加载对象型数据
Message.obtain(Handler hander)
当looper将消息取出交还给另外的handler
一、发送一个空的Message,传递一个轻量的数据;使用what标识
1、继承Handler,在Activity中写一个内部类,接收消息,在这里更新UI
class MyHandler2 extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText(msg.what+" ");
}}
2 、定义MyHandler2对象,一般为Activity的成员变量
MyHandler2 handler2=new MyHandler2();
3、在工作线程中,使用MyHandler2给UI线程发送消息
使用sendEmptyMessage(),参数为int值,传递轻量参数
public void onClick(View view){
new Thread(new Runnable() {
@Override
public void run() {
while(i<100){
i++;
handler2.sendEmptyMessage(i);
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
效果图
public class HandlerActivity_12_08 extends AppCompatActivity {
TextView textView;
MyHandler2 handler2=new MyHandler2();
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_activity_12_08);
textView= (TextView) findViewById(R.id.tvHandler_08);
}
public void onClick(View view){
new Thread(new Runnable() {
@Override
public void run() {
while(i<100){
i++;
handler2.sendEmptyMessage(i);
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
class MyHandler2 extends Handler{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
textView.setText(msg.what+" ");
}
}
}
网友评论