Application 类详解

来源:互联网 发布:淘宝店标,店铺说明 编辑:程序博客网 时间:2024/05/17 22:52

参考:http://www.2cto.com/kf/201507/412895.html 

           http://www.wfuyu.com/technology/22258.html


Application类的父类:

java.lang.Object

   ↳android.content.Context    ↳android.content.ContextWrapper     ↳android.app.Application

Android 官网介绍:

Base class for maintaining global application state. You can provide your own implementation by creating a subclass and specifying the fully-qualified name of this subclass as the "android:name" attribute in your AndroidManifest.xml's<application> tag. The Application class, or your subclass of the Application class, is instantiated before any other class when the process for your application/package is created.

Note: There is normally no need to subclass Application. In most situations, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), include Context.getApplicationContext() as a Context argument when invoking your singleton's getInstance() method.


即Application类是一个用于保存应用全局状态的基类。

1.概念:
android系统会为每个程序运行时创建一个Application类的对象且仅创建一个,所以Application可以说是单例 (singleton)模式的一个类.且application对象的生命周期是整个程序中最长的,它的生命周期就等于这个程序的生命周期。因为它是全局的单例的,所以在不同的Activity,Service中获得的对象都是同一个对象。所以通过Application来进行一些,数据传递,数据共享,数据缓存等操作。

2.作用:
(1).Application是一个基类,这个基类的作用是获取整个App的状态,我们需要自己定义一个类来继承这个基类。
(2).定义一些全局的和一些上下文都要用到的变量和方法。

3.优点:
(1).继承的方式:
生命周期随着应用程序的销毁而销毁。
(2).静态类或静态方法:
程序退出后该类或者变量不能立刻被GC回收。
当你再次进入后会发现该静态类保存的信息状态是之前的。有可能会导致程序不是你想要的初始化状态。
(3).App的进程被创建时,这个类就会被实例化,onCreate()方法就会被执行,给所有全局变量赋初期值。这样,所有的Activity就共同拥有这个类里面的变量了。

4.getContext()、getApplication()、getApplicationContext()、getActivity()的区别:
(1).getContext():获取到当前对象的上下文。
(2).getApplication():获得Application的对象
(3).getApplicationContext():获得应用程序的上下文。有且仅有一个相同的对象。生命周期随着应用程序的摧毁而销毁。就像是社会,所有的都发生在这个社会上,仅且只有一个社会。每个Activity都有自己的上下文,而整个应用只有一个上下文
(4)getActivity():获得Fragment依附的Activity对象。Fragment里边的getActivity()不推荐使用原因如下:这个方法会返回当前Fragment所附加的Activity,当Fragment生命周期结束并销毁时,getActivity()返回的是null,所以在使用时要注意判断null或者捕获空指针异常。所以只要判断getActivity()为空,就可以不再执行下面的代码,这完全不影响业务的使用。

5. 应用程序创建Context实例的情况有如下几种情况:
(1).创建Application对象时,而且整个App共一个Application对象
(2).创建Service对象时
(3).创建Activity对象时。
Activity Service Application都是Context的子类。Context是一个抽象类,具体的实现是在ContextImpl类中。因此应用程序App共有的Context数目公式为:
总Context实例个数=Service个数+Activity个数+1(Application对应的Context实例)

6.Android应用中内存泄漏问题:
(1).对Context持有一个过长的引用。对Context的引用超过它本身的生命周期。Android应用程序限制使用的堆内存是16M
(2).静态变量拥有了更多的对象引用,内存仍然不会被销毁。
总结一下:避免Context泄漏应该注意的问题:
1.使用Application这种Context类型
2.注意对Context的引用不要超过它本身的生命周期
3.谨慎使用static关键字
4.Context里如果有线程,一定要在onDestory()里及时停掉。



0 0
原创粉丝点击