1、先熟悉handler方式实现主线程和子线程互相通信方式,子线程和子线程的通信方式
如果不熟悉或者忘记了,请参考我的这篇博客 Android之用Handler实现主线程和子线程互相通信以及子线程和子线程之间的通信 http://blog.csdn.net/u011068702/article/details/75577005
2、贴上简单HandlerThread简单使用(主线程和子线程通信、子线程和子线程通信)的例子
1、activity_main.xml文件
<RelativeLayout 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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.handler.MainActivity1" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ParentToChile" />
<Button
android:layout_below="@+id/button1"
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ChileToParent" />
<Button
android:layout_below="@+id/button2"
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ChileToChile" />
</RelativeLayout>
2、MainActivity.java文件
package com.example.handler;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
public static final String TAG = "HandlerTest";
public HandlerThread mHandlerThread;
public Handler mChileHandler;
public Handler mHandlerCToP = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int id = (int) Thread.currentThread().getId();
Log.d(TAG, "mHandlerCToP currentThread id is:" + id);
}
};
public Button mButtonPtoC;
public Button mButtonCtoP;
public Button mButtonCtoC;
public Handler mHandler = new Handler();
public Handler mHandlerCtoC = null;