线程间的消息传递

YXTS122 2017-02-20 06:08:47

EventHandler.java

package com.mytest.handlertest;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
class EventHandler extends Handler
{
private NoLooperThread noLooperThread;
private OwnLooperThread ownLooperThread;
private Context context;
public EventHandler(Context context,Looper looper)
{
super(looper);
this.context=context;

}
public EventHandler()
{
super();
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.e("EventHandler", "当前线程id:------+>"+Thread.currentThread().getId());
Toast.makeText(context, "当前线程id:------+>"+Thread.currentThread().getId(), Toast.LENGTH_SHORT).show();
//可以根据msg.what执行不同的处理,这里没有这么做
switch(msg.what){
case 1:
Log.e("EventHandler",(String)msg.obj);
Toast.makeText(context, (String)msg.obj+"按钮1", Toast.LENGTH_SHORT).show();
break;
case 2:
Log.e("EventHandler",(String)msg.obj);
Toast.makeText(context, (String)msg.obj+"按钮2", Toast.LENGTH_SHORT).show();
//noLooperThread.stop();
break;
case 3:
//不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
Log.e("EventHandler", (String)msg.obj);
Toast.makeText(context, (String)msg.obj+"按钮3", Toast.LENGTH_SHORT).show();
//ownLooperThread.stop();
break;
default:
//不能在非主线程的线程里面更新UI,所以这里通过Log打印收到的消息
Log.e("EventHandler", (String)msg.obj);
Toast.makeText(context, (String)msg.obj+"按钮0", Toast.LENGTH_SHORT).show();
break;
}
}
}




HandlerTest.java
package com.mytest.handlertest;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HandlerTest extends Activity implements OnClickListener {
private Button btn1,btn2,btn3,btn4,btn5,btn6;
private boolean postRunnable;
private EventHandler mHandler;
private NoLooperThread noLooperThread;
private OwnLooperThread ownLooperThread;
private EventHandler mOtherThreadHandler;
private TextView tv;
private ReceiveMessageThread receiveMessageThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_handler_test);
btn1=(Button)findViewById(R.id.b101);
btn2=(Button)findViewById(R.id.b102);
btn3=(Button)findViewById(R.id.b103);
btn4=(Button)findViewById(R.id.b104);
btn5=(Button)findViewById(R.id.b105);
btn6=(Button)findViewById(R.id.b106);
tv=(TextView)findViewById(R.id.tv1);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
receiveMessageThread=new ReceiveMessageThread(this);
receiveMessageThread.start();

}

@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.b101:
//主线程发送消息给自己
Looper looper;
looper = Looper.myLooper(); //get the Main looper related with the main thread
//如果不给任何参数的话会用当前线程对应的Looper(这里就是Main Looper)为Handler里面的成员mLooper赋值
mHandler = new EventHandler(this,looper);
//mHandler = new EventHandler();
// 清除整个MessageQueue里的消息
mHandler.removeMessages(0);
String obj = "This main thread's message and received by itself!";
//得到Message对象
Message m = mHandler.obtainMessage(3, 1, 1, obj);
// 将Message对象送入到main thread的MessageQueue里面
mHandler.sendMessage(m);
break;
case R.id.b102:
//other线程发送消息给主线程
postRunnable = false;
noLooperThread = new NoLooperThread(this);
noLooperThread.start();
break;
case R.id.b103:
//other thread获取它自己发送的消息
tv.setText("请看其他线程接收消息的错误级别日志");
ownLooperThread = new OwnLooperThread(this);
ownLooperThread.start();
break;
case R.id.b104:
//other thread通过Post Runnable方式发送消息给主线程
postRunnable = true;
noLooperThread = new NoLooperThread(this);
noLooperThread.start();
break;
case R.id.b105:
//主线程发送消息给other thread
Looper mainLooper=Looper.myLooper();
if(null==mOtherThreadHandler){
tv.setText("please look at the error level log for other thread received message from main thread");
mOtherThreadHandler=new EventHandler(this,mainLooper);
String msgObj = "message from mainThread";
mOtherThreadHandler.removeMessages(0);
Message mainThreadMsg = mOtherThreadHandler.obtainMessage(1, 1, 1, msgObj);
mOtherThreadHandler.sendMessage(mainThreadMsg);
}
break;
case R.id.b106:
finish();
break;
}
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.handler_test, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}


NoLooperThread.java
package com.mytest.handlertest;

import android.content.Context;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

class NoLooperThread extends Thread{
private Context context;
private TextView tv;
private boolean postRunnable;
private EventHandler mNoLooperThreadHandler;

public NoLooperThread(Context context)
{
this.context=context;
}

public void run() {
Looper myLooper, mainLooper;
myLooper = Looper.myLooper();
mainLooper = Looper.getMainLooper(); //这是一个static函数
String obj;
if(myLooper == null){
mNoLooperThreadHandler = new EventHandler(context,mainLooper);
obj = "NoLooperThread has no looper and handleMessage function executed in main thread!";
Log.e("NoLooperThread", "测试1");
}
else {
mNoLooperThreadHandler = new EventHandler(context,myLooper);
obj = "This is from NoLooperThread self and handleMessage function executed in NoLooperThread!";
}
//Toast.makeText(context, obj, Toast.LENGTH_SHORT).show();
mNoLooperThreadHandler.removeMessages(0);
if(false == postRunnable){
//send message to main thread
Message m = mNoLooperThreadHandler.obtainMessage(2, 1, 1, obj);
mNoLooperThreadHandler.sendMessage(m);
Log.e("NoLooperThread", "NoLooperThread id:" + this.getId());
}else{
//下面new出来的实现了Runnable接口的对象中run函数是在Main Thread中执行,不是在NoLooperThread中执行
//注意Runnable是一个接口,它里面的run函数被执行时不会再新建一个线程
//您可以在run上加断点然后在eclipse调试中看它在哪个线程中执行
mNoLooperThreadHandler.post(new Runnable(){
@Override
public void run() {
Log.e("NoLooperThread","update UI through handler post runnalbe mechanism!");
// noLooerThread.stop();
}
});
}
}
}



OwnLooperThread.java
package com.mytest.handlertest;

import android.content.Context;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

class OwnLooperThread extends Thread{
private Context context;
private EventHandler mOwnLooperThreadHandler;
public OwnLooperThread(Context context)
{
this.context=context;
}
public void run() {
Looper.prepare();
Looper myLooper, mainLooper;
myLooper = Looper.myLooper();
mainLooper = Looper.getMainLooper(); //这是一个static函数
String obj;
if(myLooper == null){
mOwnLooperThreadHandler = new EventHandler(context,mainLooper);
obj = "OwnLooperThread has no looper and handleMessage function executed in main thread!";
}
else {
mOwnLooperThreadHandler = new EventHandler(context,myLooper);
obj = "This is from OwnLooperThread self and handleMessage function executed in NoLooperThread!";
Log.e("OwnLooperThread", "测试2");
}
//Toast.makeText(context, obj, Toast.LENGTH_SHORT).show();
mOwnLooperThreadHandler.removeMessages(0);
//给自己发送消息
Message m = mOwnLooperThreadHandler.obtainMessage(3, 1, 1, obj);
mOwnLooperThreadHandler.sendMessage(m);
Looper.loop();
}
}




...全文
173 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
YXTS122 2017-02-20
  • 打赏
  • 举报
回复
有人吗?case R.id.b102和case R.id.b104这两个执行效果怎么一样,不是它们的bpostRunnable值设置得不一样吗?一个是false,一个是true。还有ReceiveMessageThread里的handleMessage方法里的log.e()怎么没打印出来?
头发还没秃a 2017-02-20
  • 打赏
  • 举报
回复
你要问什么。。。
YXTS122 2017-02-20
  • 打赏
  • 举报
回复
ReceiveMessageThread.java
package com.mytest.handlertest;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

class ReceiveMessageThread extends Thread{
	private Handler mOtherThreadHandler;
	private Context context;
	public ReceiveMessageThread(Context context)
	{
		this.context=context;
	}
	   public void run() {   
	Looper.prepare();   
	mOtherThreadHandler = new Handler(){
		@Override
	public void handleMessage(Message msg) {
		super.handleMessage(msg);
	    Log.e("ReceiveMessageThread", (String)msg.obj);
	    Log.e("ReceiveMessageThread","当前线程id:----+>"+Thread.currentThread().getId());
	   // Toast.makeText(context, "当前线程id:----+>"+Thread.currentThread().getId(), Toast.LENGTH_SHORT).show();
	}   
	};   
	Looper.loop();   
	   }   
	}   
	  

  
activity_handler_test.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mytest.handlertest.HandlerTest"
    android:orientation="vertical" >
    
    <Button 
        android:id="@+id/b101" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/messagea"/>
    
     <Button 
        android:id="@+id/b102" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/messageb"/>
     <Button 
        android:id="@+id/b103" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/messagec"/>
    
      <Button 
        android:id="@+id/b104" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/messaged"/>
    
       <Button 
        android:id="@+id/b105" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/messagee"/>
    
        <Button 
        android:id="@+id/b106" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/messagef"/>
    
    <TextView
        android:id="@+id/tv1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</LinearLayout>  

80,361

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧