• 主线程和子线程的通讯之主线程用bundle发送数据到子线程


    package com.wangcan;

    import android.os.Bundle;
    import android.os.Handler;
    import android.os.HandlerThread;
    import android.os.Message;
    import android.app.Activity;
    import android.util.Log;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;

    public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    System.out.println("当前线程的id是:"+Thread.currentThread().getId());
    System.out.println("当前线程的名称是:"+Thread.currentThread().getName());

    HandlerThread htThread=new HandlerThread("myht");
    htThread.start();
    Handler mHandler=new Handler(htThread.getLooper()){
    @Override
    public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    //super.handleMessage(msg);
    Bundle b2= msg.getData();
    int age= b2.getInt("age");
    String name = b2.getString("name");
    Log.d("TAG", "age:" + age + ", name:" + name);
    Log.d("TAG", "handler-->" + Thread.currentThread().getId());
    Log.d("TAG", "handleMessage");
    }
    };
    Message msg = mHandler.obtainMessage();
    //将msg发送到目标对象,就是生成该msg的Handler对象

    Bundle b = new Bundle();//使用Bundle来传递数据
    b.putInt("age", 20);
    b.putString("name", "John");
    msg.setData(b);
    msg.sendToTarget();

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }
    }

  • 相关阅读:
    异常处理 try catch throw(C++)
    Kubernetes轻量级日志收集系统LokiStack
    第一章.java
    第四章.选择结构(二)
    java语法
    第三章if选择结构
    第二章.数据类型变量名和运算符
    【转载】跳槽七诫
    【转载】修改shell终端提示信息
    ubuntu11.10面板上输入法图标消失解决办法
  • 原文地址:https://www.cnblogs.com/wangcan/p/2806210.html
Copyright © 2020-2023  润新知