Android利用Bundle实现Activity间消息的传递
关于Activity之间的消息的传递。利用Bundle是一种比较方便的办法。
程序的效果是活动A向B跳转的同时发送一字符串,B读出字符串。
先在AndroidManifest.xml中定义一个新的Activity,target:
Xml代码
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ray.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestBundle"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Target"></activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ray.test"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".TestBundle"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Target"></activity>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
第一个活动的代码如下:
Java代码
package com.ray.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class TestBundle extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onTouchEvent(MotionEvent event) {
Intent intent = new Intent();
intent.setClass(TestBundle.this, Target.class);
Bundle mBundle = new Bundle();
mBundle.putString("Data", "ray'blog");//压入数据
intent.putExtras(mBundle);
startActivity(intent);
finish();
return super.onTouchEvent(event);
}
女装品牌大全
}
package com.ray.test;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
public class TestBundle extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public boolean onTouchEvent(MotionEvent event) {
Intent intent = new Intent();
intent.setClass(TestBundle.this, Target.class);
Bundle mBundle = new Bundle();
mBundle.putString("Data", "ray'blog");//压入数据
intent.putExtras(mBundle);
startActivity(intent);
finish();
return super.onTouchEvent(event);
}
}
将要跳转到的活动代码:
Java代码
package com.ray.test;
货运专家
import android.app.Activity;
import android.os.Bundle;
public class Target extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle bundle = getIntent().getExtras();
String data=bundle.getString("Data");//读出数据
setTitle(data);
}
}