主线程

public class MainActivity extends ActionBarActivity {
private Handler handler;
// private Thread mthread;
private int timer;
private TextView info;
private Button msgbtn;
xThread xthread;
private boolean running; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
info=(TextView)findViewById(R.id.info);
handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// super.handleMessage(msg);
switch (msg.what) {
case 0:
Log.i("xx", "==" + msg.obj);
info.setText("耗时" + msg.obj + "秒");
}
}
};
xthread=new xThread(handler);
msgbtn= (Button)findViewById(R.id.msgBtn);
msgbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(running){
running=false;
xthread.setRunning(false);
msgbtn.setText("开始");
}else{
running=true;
xthread.setRunning(true);
msgbtn.setText("停止");
} }
});
xthread.start();
} }

子线程

class xThread extends Thread{
private Handler mhandler;
private boolean running=true;
public xThread(Handler handler){
mhandler=handler;
}
private int t;
public void run(){
Message msg;
try {
while (true) {
if(running) {
msg = new Message();
Log.i("ggg", "==" + t);
Thread.sleep(1000);
t++;
msg.what = 0;
msg.obj = t;
mhandler.sendMessage(msg);
}
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
public void setRunning(boolean running){
this.running=running;
}
}

另:

public class MainActivity extends Activity {

    private static final String TAG = "MainThread";
private Handler mMainHandler, mChildHandler;
private TextView info;
private Button msgBtn; @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); info = (TextView) findViewById(R.id.info);
msgBtn = (Button) findViewById(R.id.msgBtn); mMainHandler = new Handler() { @Override
public void handleMessage(Message msg) {
Log.i(TAG, "Got an incoming message from the child thread - "
+ (String) msg.obj);
// 接收子线程的消息
info.setText((String) msg.obj);
} }; new ChildThread().start(); msgBtn.setOnClickListener(new View.OnClickListener() { @Override
public void onClick(View v) { if (mChildHandler != null) { //发送消息给子线程
Message childMsg = mChildHandler.obtainMessage();
childMsg.obj = mMainHandler.getLooper().getThread().getName() + " says Hello";
mChildHandler.sendMessage(childMsg); Log.i(TAG, "Send a message to the child thread - " + (String)childMsg.obj); }
}
}); } public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Stop looping the child thread's message queue"); mChildHandler.getLooper().quit();
} class ChildThread extends Thread { private static final String CHILD_TAG = "ChildThread"; public void run() {
this.setName("ChildThread"); //初始化消息循环队列,需要在Handler创建之前
Looper.prepare(); mChildHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.i(CHILD_TAG, "Got an incoming message from the main thread - " + (String)msg.obj); try { //在子线程中可以做一些耗时的工作
sleep(100); Message toMain = mMainHandler.obtainMessage();
toMain.obj = "This is " + this.getLooper().getThread().getName() +
". Did you send me \"" + (String)msg.obj + "\"?"; mMainHandler.sendMessage(toMain); Log.i(CHILD_TAG, "Send a message to the main thread - " + (String) toMain.obj); } catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }; Log.i(CHILD_TAG, "Child handler is bound to - "+ mChildHandler.getLooper().getThread().getName()); //启动子线程消息循环队列
Looper.loop();
}
}
}

Android多线程通信之Handler的更多相关文章

  1. Android多线程通信机制

    掌握Android的多线程通信机制,我们首先应该掌握Android中进程与线程是什么. 1. 进程 在Android中,一个应用程序就是一个独立的进程(应用运行在一个独立的环境中,可以避免其他应用程序 ...

  2. android 多线程Thread,Runnable,Handler,AsyncTask

    先看两个链接: 1.http://www.2cto.com/kf/201404/290494.html 2. 链接1: android 的多线程实际上就是java的多线程.android的UI线程又称 ...

  3. Android多线程:深入分析 Handler机制源码(二)

    前言 在Android开发的多线程应用场景中,Handler机制十分常用 接下来,深入分析 Handler机制的源码,希望加深理解 目录 1. Handler 机制简介 定义一套 Android 消息 ...

  4. Android多线程机制和Handler的使用

    参考教程:iMooc关于Handler,http://www.imooc.com/learn/267 参考资料:Google提供Android文档Communicating with the UI T ...

  5. Android 多线程通信 访问网络

    package org.rongguang.testthread; import android.app.Activity; import android.os.Bundle; import andr ...

  6. Android多线程编程<二>Handler异步消息处理机制之Message

      Message(消息):       一. Message的字段:    在Android中,Message作为线程之间(主要是子线程和UI主线程之间)数据交换的载体,通过Handler去传递.它 ...

  7. Android多线程----异步消息处理机制之Handler详解

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  8. Android多线程分析之三:Handler,Looper的实现

    Android多线程分析之三:Handler,Looper的实现 罗朝辉 (http://www.cnblogs.com/kesalin/) CC 许可,转载请注明出处 在前文<Android多 ...

  9. Android多线程源码学习笔记一:handler、looper、message、messageQueue

    最近在学习Android多线程相关知识的源码,现在把自己的笔记整理一下,写出来加深印象. Android多线程通讯的核心是handler.looper.message.messageQueue,这篇文 ...

随机推荐

  1. http请求及模拟浏览器发送http请求

    /**    *测试新增图片   * @throws IOException    * @throws HttpException    * @throws SAXException    * @th ...

  2. http://blinkfox.com/shi-yong-spring-aoplai-tong-ji-fang-fa-de-zhi-xing-shi-jian/

    http://blinkfox.com/shi-yong-spring-aoplai-tong-ji-fang-fa-de-zhi-xing-shi-jian/ spring-aop.xml @Com ...

  3. 点击空白处隐藏div

    class="bigPic"的div是被显示或隐藏的div,另外.case > ul > li是class="bigPic"的父级元素 $(&quo ...

  4. NYU Hand Pose Dataset

    http://cims.nyu.edu/~tompson/NYU_Hand_Pose_Dataset.htm#overview

  5. for循环计数

    1.巧用for循环计数,将文件每10行写到另一个文件,每遍历一行i就加1 with open('/etc/passwd') as f1, open('/tmp/passwd','w') as f2: ...

  6. python_中文乱码问题

    1. 编码和解码的概念:    编码是将源对象内容按照一种标准转换为一种标准格式内容.    解码是和编码对应的,它使用和编码相同的标准将编码内容还原为最初的对象内容. 2. python中的编码和解 ...

  7. ORA-28056:Writing audit records to Windows EventLog failed的问题

    右键“我的电脑”--‘管理’--事件查看器--点击左边的日志(应用程序日志.安全日志.系统日志),右击某个项目,选择‘清除所有事件'即可删除.

  8. 启动MFC程序的时候报错:0xC0000005: 读取位置 0x00000000 时发生访问冲突

    此程序的结构是 MouseCap.h #pragma once #include <afxwin.h> class MouseCapApp : public CWinApp { publi ...

  9. redmine发送邮件

    vim /data/server/redmine/apps/redmine/htdocs/config/configuration.yml default: # Outgoing emails con ...

  10. BeanUtils设置字段值失败问题

    package org.apache.commons.beanutils; import static org.junit.Assert.*; import java.beans.BeanInfo; ...