关于android中是否可以使用全局变量,当然可以。做Java的人肯定都用过全局变量了,使用方法无非是定义一个静态变量,public类型,这样在其他类中就可以直接调用了,android中也可以这样使用。

但是,android中这样使用全局变量是不是最符合android的架构呢,在国外的论坛里找到了下面的解决办法:

ThemoregeneralproblemyouareencounteringishowtosavestateacrossseveralActivitiesandallpartsofyourapplication.Astaticvariable(forinstance,asingleton)isacommonJavawayofachievingthis.Ihavefoundhowever,thatamoreelegantwayinAndroidistoassociateyourstatewiththeApplicationcontext.

--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Applicationcontext。

Asyouknow,eachActivityisalsoaContext,whichisinformationaboutitsexecutionenvironmentinthebroadestsense.Yourapplicationalsohasacontext,andAndroidguaranteesthatitwillexistasasingleinstanceacrossyourapplication.
--每个Activity都是Context,其包含了其运行时的一些状态,android保证了其是singleinstance的。

Thewaytodothisistocreateyourownsubclassofandroid.app.Application,andthenspecifythatclassintheapplicationtaginyourmanifest.NowAndroidwillautomaticallycreateaninstanceofthatclassandmakeitavailableforyourentireapplication.YoucanaccessitfromanycontextusingtheContext.getApplicationContext()method(ActivityalsoprovidesamethodgetApplication()whichhastheexactsameeffect):
--方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。

下面看一下Demo:

[java] view plain copy
  1. classMyAppextendsApplication{
  2. privateStringmyState;
  3. publicStringgetState(){
  4. returnmyState;
  5. }
  6. publicvoidsetState(Strings){
  7. myState=s;
  8. }
  9. }
  10. classBlahextendsActivity{
  11. @Override
  12. publicvoidonCreate(Bundleb){
  13. ...
  14. MyAppappState=((MyApp)getApplicationContext());
  15. Stringstate=appState.getState();
  16. ...
  17. }
  18. }


Thishasessentiallythesameeffectasusingastaticvariableorsingleton,butintegratesquitewellintotheexistingAndroidframework.Notethatthiswillnotworkacrossprocesses(shouldyourappbeoneoftherareonesthathasmultipleprocesses).
--这个效果就是使用静态变量是一样的,但是其更符合android的架构体系。

使用这种方法的话需要在AndroidManifest.xml中配置一下:

<applicationandroid:name=".MyApp"android:icon="@drawable/icon"android:label="@string/app_name">

更多相关文章

  1. Google I/O Android官方新体系架构之:Lifecycle
  2. android 中的全局变量问题
  3. 在Android中如何使用全局变量--Application context
  4. android音频架构
  5. android底层开发-android基础架构
  6. [置顶] 关于Android NDK中如何调用第三方静态库--live555
  7. Android智能推荐、MVP架构电商应用、markdown编辑器、多种动画效

随机推荐

  1. android获取各路径下的文件流
  2. Android:证书生成与应用
  3. Android中判断是否有声音在播放
  4. Android 通过AudioTrack播放CAF音频
  5. 获取Android设备电池信息
  6. Qt 5.7.0 (32 bit) 配置 Android 环境
  7. Android(安卓)Debug Bridge
  8. android之发送短信的方法研究
  9. Android Apk脱壳(360加固)
  10. Android 后台发邮件