在Android中使用Intent在兩個(gè)Activity間傳遞數(shù)據(jù)時(shí),只能是基本類型數(shù)據(jù),或者是序列化對(duì)象。Intent是一種基于消息的進(jìn)程內(nèi)和進(jìn)程間通信模型,當(dāng)我們需要在我們應(yīng)用程序內(nèi)部,多個(gè)Activity間進(jìn)行復(fù)雜數(shù)據(jù)對(duì)象共享交互時(shí),使用Intent就顯得很不方便。此時(shí),我們就需要一種數(shù)據(jù)共享的機(jī)制來(lái)實(shí)現(xiàn)。當(dāng)然,直接使用java語(yǔ)言中的靜態(tài)變量是可以的,但在Android中有更為優(yōu)雅的實(shí)現(xiàn)方式。
【轉(zhuǎn)自:
http://www.javaeye.com/topic/552758】
【原文鏈接:http://stackoverflow.com/questions/708012/
android-how-to-declare-global-variables】
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.
--如想在整個(gè)應(yīng)用中使用,在java中一般是使用靜態(tài)變量,而在
android中有個(gè)更優(yōu)雅的方式是使用
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.
--每個(gè)Activity 都是Context,其包含了其運(yùn)行時(shí)的一些狀態(tài),
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):
--方法是創(chuàng)建一個(gè)屬于你自己的
android.
app.
Application的子類,然后在manifest中申明一下這個(gè)類,這是
android就為此建立一個(gè)全局可用的實(shí)例,你可以在其他任何地方使用Context.getApplicationContext()方法獲取這個(gè)實(shí)例,進(jìn)而獲取其中的狀態(tài)(變量)。
- 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();
- ...
- }
- }