Activity共享变量之Application context

Android中在不同Activity中传递变量,通常使用Intent中Bundle添加变量的操作方法。

在多个Activity中经常使用同一个变量时,使用Bundle就会比较麻烦,每次调用Activity都需要设置一次。如想在整个应用程序中使用,在java中通常是使用静态变量,而在android中有个更优雅的方式是使用Application context。新建一个类,继承自Application。

在AndroidManifest.xml的application加个name属性就可以了,如下面所示:

使用时:

英文引用:

The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.

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

As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single 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 and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):

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

Android程序中访问资源时需要提供Context,一般来说只有在各种component中(Activity, Provider等等)才能方便的使用api来获取Context, 而在某些工具类中要获取就很麻烦了。为此,我们可以自定义一个Application类来实现这种功能。

然后在manifest中中加入name="mypackage.MyApplication"就可以在任意类中使用MyApplication.getInstance()来获取应用程序Context了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,428评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,404评论 19 139
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 11,727评论 0 17
  • 2017.11.23 1、昨天早上在时间效率,限定时间上还是做得很差,做了很多无关紧要的事!好习惯的养成真的不是一...
    张彦博Burgess阅读 1,176评论 0 0
  • 最近发现很多复古的东西,看上去就很可爱 在龙洞堡机场吃的老素粉,碗有点象石锅拌饭那种,大概是粗瓷,摸着...
    雪舞天2013阅读 1,768评论 0 1