方法一:通过android.content.Intent传递数据,只能传递基类型
存储数据
// 方法一:用intent传递数据
intent.putExtra("string", str);
读取数据
// 方法一:用intent传递数据
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
str += "Fonction 1: " + bundle.getString("string") + "\n";
方法二:通过android.content.SharedPreferences传递数据,只能传递基类型
存储数据
// 方法二:用SharedPreferences传递数据
SharedPreferences preferences = getSharedPreferences("test", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("string", str);
editor.commit();
读取数据
// 方法二:用SharedPreferences传递数据
SharedPreferences preferences = this.getSharedPreferences("test", MODE_PRIVATE);
str += "Fonction 2: " + preferences.getString("string", "not found") + "\n";
方法三:自定义继承Application的类传递数据,可以传递基类型和自定义类型,需要在manifest中注册
manifest中注册
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name="mytest.xml.MyApp">
自定义继承Application的类
public class MyApp extends Application {
private String str;
private Obj obj;
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public Obj getObj() {
return obj;
}
public void setObj(Obj obj) {
this.obj = obj;
}
}
存储数据
// 方法三:用Application自定义类传递数据
MyApp app = (MyApp)getApplicationContext();
app.setStr(str);
app.setObj(obj);
读取数据
// 方法三:用Application自定义类传递数据
MyApp app = (MyApp)this.getApplicationContext();
str += "Fonction 3 (string): " + app.getStr() + "\n";
str += "Fonction 3 (object): " + app.getObj().getMess(); // app.getObj返回自定义Obj类实例,getMess()方法返回类内定义的String内容