15-多线程编程(04-Handler和Message二)
2013-07-16 17:31
295 查看
package net.csdn.leigo.handler.message; import net.csdn.leigo.handler.R; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.TextView; public class MainActivity extends Activity { private TextView mMsgTextView; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); if (msg.what == 3) { int arg1 = msg.arg1; int arg2 = msg.arg2; int what = msg.what; Object obj = msg.obj; Bundle bundle = msg.getData(); String data = bundle.getString("data"); mMsgTextView.setText("arg1:" + arg1 + ", arg2:" + arg2 + ", what:" + what + ", obj:" + obj.toString() + ", data:" + data); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mMsgTextView = (TextView) findViewById(R.id.tv_msg); } public void sendMessage(View v) { new Thread(new Runnable() { @Override public void run() { // ----------------------------------第一种方式----------- // Message msg = Message.obtain(); // msg.arg1 = 100; // msg.arg2 = 200; // msg.what = 1; // msg.obj = " hello "; // handler.sendMessage(msg); // ----------------------------------------------------- // ----------------------------------第二种方式----------- // Message msg = Message.obtain(handler); // msg.arg1 = 100; // msg.arg2 = 200; // msg.what = 2; // msg.obj = " world "; // msg.sendToTarget(); // ----------------------------------------------------- // ----------------------------------第三种方式----------- //Message有很多重载方法,具体查看API,这里通过Bundle传递一个参数 Message msg = Message.obtain(handler, 3); Bundle bundle = new Bundle(); bundle.putString("data", "hello world"); msg.obj = " android "; msg.setData(bundle); msg.sendToTarget(); } }).start(); } }
相关文章推荐
- 15-多线程编程(03-Handler和Message一)
- 安卓多线程编程系列7:使用Looper的不同方式(子线程中实例化Handler方式)
- Java多线程编程-(15)-读写锁ReentrantReadWriteLock深入分析
- Android多线程编程(异步通信)--->Handler和AsyncTask
- 04-0. 求符合给定条件的整数集(15)
- 15-04-12 PDO新问题
- ym——Android从零开始(15)(Activity启动模式、ANR异常、Handler)(新)
- 04-0. 求符合给定条件的整数集(15)
- 15-04-常用对象API(String类-常见功能-获取_2)
- 字符串-04. 字符串逆序(15)
- 字符串-04. 字符串逆序(15)
- PAT_B_字符串-04. 字符串逆序(15)
- 04-4. 猜数字游戏(15)
- 04-2. 打印九九口诀表(15)
- 04-0. 求符合给定条件的整数集(15)
- 字符串-04. 字符串逆序(15)
- obj-c编程15[Cocoa实例04]:基于Core Data的多文档程序示例[未完待续]
- 多线程编程(15) - 多线程同步之 WaitableTimer (等待定时器对象)[续]
- 04-0. 求符合给定条件的整数集(15)
- 多线程编程(15) - 多线程同步之 WaitableTimer (等待定时器对象)[续]