当前位置: 代码迷 >> Android >> 安卓Handel跟Message(二)
  详细解决方案

安卓Handel跟Message(二)

热度:45   发布时间:2016-04-28 06:03:45.0
安卓Handel和Message(二)

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent">    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="点击" /></RelativeLayout>


MainActivity

package com.example.android_handler;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.R.integer;import android.app.Activity;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity { private Button button; private Handler handler = new Handler() {  @Override  public void handleMessage(Message msg) {   // 取得消息数据   int what = msg.what;   int arg1 = msg.arg1;   int arg2 = msg.arg2;   Object object = msg.obj;   Bundle bundle = msg.getData();   String[] arr = bundle.getStringArray("haha");   String str = new String();   for (String temp : arr) {    str += temp;   }   // 显示消息   System.out.println("--what-->" + what);   System.out.println("--arg1-->" + arg1);   System.out.println("--arg2-->" + arg2);   System.out.println("--object-->" + object);   System.out.println("--arr-->" + str);  }; }; @Override protected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  button = (Button) this.findViewById(R.id.button1);  button.setOnClickListener(new OnClickListener() {   @Override   public void onClick(View v) {    // TODO Auto-generated method stub    new Thread(new MyThread()).start();// 开启线程   }  }); } public class MyThread implements Runnable {  @Override  public void run() {   // TODO Auto-generated method stub   Message message = Message.obtain(handler, 0, 1, 2, "dashu");   Bundle bundle = new Bundle();   bundle.putStringArray("haha", new String[] { "dashu", "meizi" });   message.setData(bundle);   message.sendToTarget();// 发送消息  } } @Override public boolean onCreateOptionsMenu(Menu menu) {  // Inflate the menu; this adds items to the action bar if it is present.  getMenuInflater().inflate(R.menu.main, menu);  return true; }}


 

  相关解决方案