方法一:通過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內容