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();??
- ????...??
- ??}??
- }??
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).?
--這個效果就是使用靜態變量是一樣的,但是其更符合android的架構體系。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
