Android中的Application类

来源:互联网 发布:ipad写毛笔字软件 编辑:程序博客网 时间:2024/06/05 03:07

在官方文档中Application的解释如下:

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's <application> tag, which will cause that class to be instantiated for you when the process for your application/package is created.

There is normally no need to subclass Application. In most situation, 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), the function to retrieve it can be given a Context which internally usesContext.getApplicationContext() when first constructing the singleton.

SDK中的描述:Application类是为了那些需要保存全局变量设计的基本类,你可以在AndroidManifest.xml的<application>标签中进行自己的实现,这样的结果是:当你的       application或者包被建立的时候将引起那个类被建立。

我的理解就是application是用来保存全局变量的,并且是在package创建的时候就跟着存在了。所以当我们需要创建全局变量的时候,不需要再像j2se那样需要创建public权限的static变量,而直接在application中去实现。只需要调用Context的getApplicationContext或者Activity的getApplication方法来获得一个application对象,再做出相应的处理。


例如Launcher模块中;它自己就写了个application,在AndroidManifest.xml中将它进行了设置:

<application
        android:name="com.android.launcher2.MyApp">

</application>

对于他的设置可以参考这个模块。


对于一些应用程序需要建立自己的主文件夹来保存不同类型的数据,就可以把mkdir的代码写到这个类里面,如下:

import java.io.File;import android.app.Application;import android.os.Environment;public class MyApp extends Application{@Overridepublic void onCreate() {// TODO Auto-generated method stubsuper.onCreate();File f = new File(Environment.getExternalStorageDirectory()+"/TestSyncListView/");if(!f.exists()){f.mkdir();}}}



原创粉丝点击