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 应用架构组件(Architecture Components)实践
  2. Android 基础总结:(一)Android系统架构
  3. Android快速开发架构PlanA(四),网络请求篇,划重点(必考)
  4. 社区讨论:Android的架构设计
  5. Android 核心分析(12) -----Android GEWS窗口管理之基本架构原理
  6. Android Camera的接口与架构介绍
  7. Android Battery 架构

随机推荐

  1. Android实现宫格图片连续滑动效果
  2. android 9Path图片的使用
  3. Android(安卓)conversion to dalvik form
  4. Android网络请求发展简史和RxJava+Retrof
  5. Android中三种常用解析XML的方式(DOM、SAX
  6. Android事件分发机制完全解析,带你从源码
  7. android每日一问2【2011-8-28】
  8. Android多媒体学习三:实现自己的Camera
  9. 【Android(安卓)开发】:数据存储之File文
  10. Android之3D动画效果