zoukankan      html  css  js  c++  java
  • java 中Handler 和Runnable 的使用 异步发送消息 转

    public class MainActivity extends Activity {
    TextView text1, text2;
    Button button;
    Thread th;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    text1 = (TextView)findViewById(R.id.text1);
    text2 = (TextView)findViewById(R.id.text2);
    button = (Button)findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub

    th = new Thread(runnable);
    th.start();
    }
    });
    }
    Handler myHandler = new Handler(){
    @Override
    public void handleMessage(Message msg) {
    // TODO Auto-generated method stub
    switch (msg.what) {
    case 1:
    System.out.println("-----------1--------------");
    System.out.println(msg.getData().getString("s1"));
    System.out.println(msg.getData().getString("s2"));
    try{
    text1.setText(msg.getData().getString("s1"));
    text2.setText(msg.getData().getString("s1"));
    }catch(Exception e){
    e.printStackTrace();
    }
    break;

    default:
    break;
    }
    super.handleMessage(msg);
    }
    };

    Runnable runnable = new Runnable() {
    @Override
    public void run() {
    // TODO Auto-generated method stub
    String s1 = "fsdfsgfdsgdfgfdgdhshshs";
    String s2 = "fsfsdgdshdhdshrehreherh";

    Message msg = new Message();
    msg.what = 1;
    Bundle bundle = new Bundle();
    bundle.putString("s1", s1);
    bundle.putString("s2", s2);
    msg.setData(bundle);
    MainActivity.this.myHandler.sendMessage(msg);
    }
    };
    }

  • 相关阅读:
    接口测试用例设计方法
    接口测试的总结文档
    数据库操作语句类型(DQL、DML、DDL、DCL)简介
    MySQL基础学习笔记
    Python2爬取内涵段子
    Python编程笔记
    Python核心编程笔记--动态属性
    Python核心编程笔记--私有化
    Python核心编程笔记--浅拷贝与深拷贝
    python核心编程笔记--模块的导入
  • 原文地址:https://www.cnblogs.com/Jerseyblog/p/3732868.html
Copyright © 2011-2022 走看看