Activity共享变量之Application context

来源:互联网 发布:老凤祥淘宝旗舰店 编辑:程序博客网 时间:2024/05/16 17:44

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中<application>中加入name="mypackage.MyApplication"就可以在任意类中使用MyApplication.getInstance()来获取应用程序Context了。

 

0 0
原创粉丝点击