Android学习笔记——Bundle

该工程的功能是实现不同线程之间数据的传递

 

以下代码是MainActivity.java中的代码

package com.example.bundle;



import android.app.Activity;

import android.os.Bundle;

import android.os.Handler;

import android.os.HandlerThread;

import android.os.Looper;

import android.os.Message;

import android.view.Menu;

import android.view.MenuItem;



public class MainActivity extends Activity {



    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //打印了当前线程的ID

        System.out.println("Activity-->"  + Thread.currentThread().getId());

        //生成一个HandleThread对象,实现了使用Looper来处理消息队列的功能,这个类由android程序框架提供

        HandlerThread handlerThread = new HandlerThread("handler_thread");

        //在使用HandlerThread的getLooper()方法之前,必须先调用该类的start()

        handlerThread.start();

        MyHandler myHandler = new MyHandler(handlerThread.getLooper());

        Message msg = myHandler.obtainMessage();

        //msg.obj="abc";

        //将msg发送到目标对象,所谓的目标对象,就是生成该msg对象的handler对象

        Bundle b = new Bundle();

        b.putInt("age", 20);

        b.putString("name", "John");

        msg.setData(b);

        msg.sendToTarget();

    }

    

    class MyHandler extends Handler{

        public MyHandler(){

            

        }

        public MyHandler(Looper looper){

            //super调用父类

            super(looper);

        }

        public void handleMessage(Message msg){

            //String s = (String)msg.obj;

            Bundle b = msg.getData();

            int age = b.getInt("age");

            String name = b.getString("name");

            System.out.println("age is " + age +", name is " + name);

            System.out.println("Handler-->" + Thread.currentThread().getId());

            System.out.println("handlerMessage");

        }

    }

}


以下代码是activity_main.xml中的代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/LinearLayout1"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical"

    tools:context="${relativePackage}.${activityClass}" >



    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="@string/hello_world" />



</LinearLayout>

 

你可能感兴趣的:(Android学习)