1. 程式人生 > >多個Activity之間共享資料的方式

多個Activity之間共享資料的方式

現在要做一個專案,多個Activity之間要共享資料,所以要考慮共享資料的方式。

其實有如下5種方式:

1.基於訊息的通訊機制  Intent ---bundle ,extra

資料型別有限,比如遇到不可序列化的資料Bitmap,InputStream, 或者LinkList連結串列等等資料型別就不太好用。

2. 利用static靜態資料,public static成員變數;

3.基於外部儲存的傳輸,  File/Preference/ Sqlite ,如果要針對第三方應用需要Content Provider

4.基於IPC的通訊機制context 與Service之間的傳輸,如Activity與Service之間的通訊,定義AIDL介面檔案。

5. 基於Application Context

這裡面我覺得第五種方法更具普適性,在網上找了篇講解得好的文章,原文如下:

在Android中使用Intent在兩個Activity間傳遞資料時,只能是基本型別資料,或者是序列化物件。Intent是一種基於訊息的程序內和程序間通訊模型,當我們需要在我們應用程式內部,多個Activity間進行復雜資料物件共享互動時,使用Intent就顯得很不方便。此時,我們就需要一種資料共享的機制來實現。當然,直接使用java語言中的靜態變數是可以的,但在Android中有更為優雅的實現方式。


The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.


--如想在整個應用中使用,在java中一般是使用靜態變數,而在android中有個更優雅的方式是使用Application context。


As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.


--每個Activity 都是Context,其包含了其執行時的一些狀態,android保證了其是single instance的。


The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):


--方法是建立一個屬於你自己的android.app.Application的子類,然後在manifest中申明一下這個類,這是android就為此建立一個全域性可用的例項,你可以在其他任何地方使用Context.getApplicationContext()方法獲取這個例項,進而獲取其中的狀態(變數)。

class MyApp extends Application {  
  private String myState;  
  public String getState(){  
    return myState;  
   }  
  public void setState(String s){  
     myState = s;  
   }  
}  
class Blah extends Activity {  
  @Override 
  public void onCreate(Bundle b){  
     ...  
     MyApp appState = ((MyApp)getApplicationContext());  
     String state = appState.getState();  
     ...  
   }  
}

對於Application的生命週期,今天測試了一下,Application型別在該APP被install的時候就已經例項化了,並且onCreate也已經被呼叫了。

如果需要建立型別裡面可能需要用到的物件的話,就可以在建構函式裡面實現,但是如果需要將該型別bind Service或者registerReceiver等操作時,需要將這些操作放到onCreate中,否則會丟擲異常。其原因主要是這個物件還沒有建立完成,此時你用這個物件來bindservice必然會出現意想不到的情況,所以在使用時還需要注意。