有主线程发送message给子线程

  通常我们在处理耗时任务时候都会通过新建线程来处理,当任务处理完后通过Handler将结果发送回主线程。比如下面示例:

 package com.example.testlistener;

 import java.util.Timer;
import java.util.TimerTask; import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast; public class MainActivity extends Activity {
EditText txt;
final Handler hander = new Handler(){
public void handleMessage(android.os.Message msg) {
if(msg.what == 0x1234){
Toast.makeText(MainActivity.this, msg.arg1 + "", 1000).show();
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); new Timer().schedule(new TimerTask() {
int i = 0;
@Override
public void run() {
i++;
Message msg = new Message();
msg.what = 0x1234;
msg.arg1 = i;
hander.sendMessage(msg);
}
}, 0, 2000);
} }

  那么,我们能不能通过Handler从主线程发送消息给子线程呢?答案是肯定的,需要用到Looper.prepare()和Looper.loop()。如下面的代码:

 public class MainActivity extends Activity {
EditText txt;
Button bt;
TestThread testThread;
int j = 0; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (EditText) findViewById(R.id.txt);
bt = (Button) findViewById(R.id.bn);
testThread = new TestThread();
testThread.start();
bt.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
j++;
Message msg = new Message();
msg.what = 0x1000;
msg.arg1 = j;
testThread.thander.sendMessage(msg);
}
}); } //自定义子线程
class TestThread extends Thread{
public Handler thander;
@Override
public void run() {
//创建一个Looper对象
Looper.prepare();
thander = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what == 0x1000){
System.out.println("j = " + msg.arg1);
//txt.setText(msg.arg1 + "");
}
}
};
//启动Looper
Looper.loop();
}
} }
上一篇:Date Time Picker控件


下一篇:各种LICENSE的作用--GET