日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

android中使用Application實現(xiàn)全局變量

 dddTTLee 2011-04-29
 
woa,找到一個和我有類似需求的問題,其下給出了不錯的解決方案,也正是我之前想到的,這種方法貌似很方便。

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.

--如想在整個應(yīng)用中使用,在java中一般是使用靜態(tài)變量,而在android中有個更優(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.
--每個Activity 都是Context,其包含了其運行時的一些狀態(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)建一個屬于你自己的android.app.Application的子類,然后在manifest中申明一下這個類,這是android就為此建立一個全局可用的實例,你可以在其他任何地方使用Context.getApplicationContext()方法獲取這個實例,進(jìn)而獲取其中的狀態(tài)(變量)。

給個例子:
Java代碼
  1. class MyApp extends Application {   
  2.   
  3.   private String myState;   
  4.   
  5.   public String getState(){   
  6.     return myState;   
  7.   }   
  8.   public void setState(String s){   
  9.     myState = s;   
  10.   }   
  11. }   
  12.   
  13. class Blah extends Activity {   
  14.   
  15.   @Override  
  16.   public void onCreate(Bundle b){   
  17.     ...   
  18.     MyApp appState = ((MyApp)getApplicationContext());   
  19.     String state = appState.getState();   
  20.     ...   
  21.   }   
  22. }  


This has essentially the same effect as using a static variable orsingleton, but integrates quite well into the existing Androidframework. Note that this will not work across processes (should yourapp be one of the rare ones that has multiple processes).
--這個效果就是使用靜態(tài)變量是一樣的,但是其更符合android的架構(gòu)體系。
 
 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多