Android中如何使用全局变量--Applicationcontext()

关于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

class MyApp extends Application {private String myState;public String getState(){return myState;}public void setState(String s){myState = s;}}class Blah extends Activity {@Overridepublic void onCreate(Bundle b){...MyApp appState = ((MyApp)getApplicationContext());String state = appState.getState();...}}

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

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

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

更多相关文章

  1. 好用的Android库
  2. Day3.4--Android简单UI控件之ImageView以及ScaleType的使用
  3. Dagger 2 在 Android(安卓)上的使用(六)
  4. android TextView 阴影效果,和使用style学习
  5. Android(安卓)测试工具集01
  6. Android(安卓)支持多屏幕机制
  7. eclipse android开发环境 bug CDT包含路径名无法修改(JNI开发使用
  8. Android(安卓)编码规范
  9. 在 Android(安卓)上使用 XML

随机推荐

  1. html5-开发起步使用工具
  2. 使用materialize css在不同页面上显示不
  3. 从数据库中读出来的是html标签,如何转换
  4. HTML表单学习1——表单基础
  5. 学习html5第三天
  6. 如何使用CSS在HTML文档中插入换行符
  7. vim 生成html 高亮
  8. 如何使用meta在“NEW”选项卡中重定向
  9. 在回发之前在Jquery LinkBut​​ton中验
  10. Angular2-对象作为无线电输入值