使用Handler实现主线程与子线程之间互相传递消息

来源:互联网 发布:淘宝消保加入步骤图 编辑:程序博客网 时间:2024/04/28 12:09
public class MainActivity extends Activity implements Handler.Callback{private Handler mHandler;private Handler mMainHandler;private static final int EXPRESSION = 2;private static final int RECV_EXPRESSION = 4;private static final String TAG = "MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mMainHandler = new Handler(getMainLooper(),this);HandlerThread handlerThread = new HandlerThread("BackgroundThread");handlerThread.start();mHandler =  new Handler(handlerThread.getLooper(),this);Button btnExpression = (Button)findViewById(R.id.btnExpression);btnExpression.setOnClickListener(new OnClickListener(){public void onClick(View v) {mHandler.sendEmptyMessage(EXPRESSION);}});}@Overrideprotected void onDestroy() {super.onDestroy();mHandler.getLooper().quit();}public boolean handleMessage(Message msg) {//单独线程处理消息switch(msg.what){case EXPRESSION://处理表情Log.i(TAG,"收到表情消息");mMainHandler.sendEmptyMessage(RECV_EXPRESSION);break;case RECV_EXPRESSION://主线程界面出现提示框Log.i(TAG,"收到子线程发来的消息");Toast.makeText(getApplicationContext(), "收到子线程打来的消息", Toast.LENGTH_SHORT).show();break;default:break;}//回收消息对象//msg.recycle();此行代码会带来异常return true;}}
在程序中实现了Handler.CallBack接口,可以在handleMessage回调方法里同时处理主线程发给子线程的数据和子线程向主线程发来的数据。 handler发送消息的方法简介:sendMessage()发送数据对象为message,message.what一般用于标识数据类型,arg1,arg2一般用于传递额外数据,object用于传递对象,如果遇到需要传递复杂数据,则可以使用bundle设置数据,再message.setData(bundle),再在handleMessage方法中message.getData()来解析对应的bundle对象。sendEmptyMessage等方法可参阅开发文档使用
0 0