• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
浅时光
我喜欢,驾驭着代码在风驰电掣中创造完美!我喜欢,操纵着代码在随必所欲中体验生活!我喜欢,书写着代码在时代浪潮中完成经典!每一段新的代码在我手中诞生对我来说就象观看刹那花开的感动!
博客园    首页    新随笔    联系   管理    订阅  订阅

Android多线程通信之Handler

主线程

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();
        }
    }
}

 

posted @ 2015-09-16 12:04  浅时光  阅读(209)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3