android定义全局变量

系统 1439 0

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()方法获取这个实例,进而获取其中的状态(变量)。 

给个例子: 

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). 
--这个效果就是使用静态变量是一样的,但是其更符合android的架构体系。

android定义全局变量


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论