何为Application,有何用途?Google官方文档是这样说的:维护全局应用程序的状态,使用的时候继承于它创建一个子类即可,同时在AndroidManifest.xml文件的<application>
标签的name属性制定它的名字,也就是子类名称。当应用程序的包被创建的时候这个类就会被实例化,而且它的生命周期和应用程序是一样的。不过Google在下面的提示中也说道大多数情况下不需要使用这个类,因为如果应用程序使用了单例模式的话,效果和Application提供的事一样的,而且也更加容易控制、规范。
关于Application类有以下公开方法:
其中最常用的就是onCreaet()、onTerminate()以及onLowMemory()方法,onCreaet()它会在这个类实例化的时候调用(这个地方需要十分注意,它只会在程序第一次启动的时候调用,不是每次都调用,因为Application类会在创建包的时候初始化),onTerminate()会在app关闭的时候调用,onLowMemory()是在内存过低的情况下调用的。那onTerminate()是干什么用的呢?网上介绍说是在程序终结的时候调用,从下面的实例中也是这样用的。不过在Google的开发文档以及很多书籍对这个类的用法很少提及,但实际开发情况是如何的呢。不妨反编译几个常用的app一看究竟,因为涉及到一些因素就不方便说是哪个app,以代号表明。
1、app_1
先把代码贴出来,因为这个app的Application的实现比较简单,就先拿出来说。
import android.annotation.TargetApi; import android.app.Application; import android.content.Context; import android.os.Build.VERSION; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import java.io.PrintStream; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpProtocolParams; public class MyApplication extends Application { private HttpClient httpClient; public boolean isLogin = false; private HttpClient createHttpClient() { BasicHttpParams localBasicHttpParams = new BasicHttpParams(); HttpProtocolParams.setVersion(localBasicHttpParams, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(localBasicHttpParams, "ISO-8859-1"); HttpProtocolParams.setUseExpectContinue(localBasicHttpParams, true); HttpConnectionParams.setConnectionTimeout(localBasicHttpParams, 20000); HttpConnectionParams.setSoTimeout(localBasicHttpParams, 20000); HttpConnectionParams.setSocketBufferSize(localBasicHttpParams, 8192); SchemeRegistry localSchemeRegistry = new SchemeRegistry(); localSchemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); localSchemeRegistry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); return new DefaultHttpClient(new ThreadSafeClientConnManager
(localBasicHttpParams, localSchemeRegistry), localBasicHttpParams); } public static void initImageLoader(Context paramContext) { ImageLoaderConfiguration localImageLoaderConfiguration = new ImageLoaderConfiguration.Builder(paramContext).
threadPriority(3).denyCacheImageMultipleSizesInMemory().discCacheFileNameGenerator(new Md5FileNameGenerator()).
tasksProcessingOrder(QueueProcessingType.LIFO).writeDebugLogs().build(); ImageLoader.getInstance().init(localImageLoaderConfiguration); } private void shutdownHttpClient() { if ((this.httpClient != null) && (this.httpClient.getConnectionManager() != null)) { this.httpClient.getConnectionManager().shutdown(); } } public HttpClient getHttpClient() { return this.httpClient; } @TargetApi(9) public void onCreate() { super.onCreate(); this.httpClient = createHttpClient(); System.out.println(Build.VERSION.SDK_INT); initImageLoader(getApplicationContext()); } public void onLowMemory() { super.onLowMemory(); shutdownHttpClient(); } public void onTerminate() { super.onTerminate(); shutdownHttpClient(); } public static class Config { public static final boolean DEVELOPER_MODE; } } |
从import导入的包就可以看出来,在这个类里面使用了强大的universalimageloader异步加载图片以及使用的apache的HttpClient。然后整体看一下这个类,发现它不仅重载了
onCreate()方法,还重载了onLowMemory()以及onTerminate()方法。onLowMemory()顾名思义就是在Android系统内存低的情况下调用的,可以在这个方法里面做一下释放内存的功能。
那就从onCreate()方法开始,里面代码如下:
this.httpClient = createHttpClient(); System.out.println(Build.VERSION.SDK_INT); initImageLoader(getApplicationContext()); |
第一个方法,创建httpClient 的对象,至于方法的具体细节就不介绍了,不是本文讨论重点,下同。第二个方法就是初始化universalimageloader了。总体来说这个app的Application的实现还是比较简单的,也比较容易理解。接下来介绍一个稍微复杂一点的。
2、app_2
import android.app.Application; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.os.Bundle; import android.os.Environment; import android.widget.Toast; import com.baidu.mapapi.BMapManager; import com.baidu.mapapi.MKGeneralListener; import com.baidu.mapapi.MKLocationManager; import java.io.File; public class App extends Application { public static App app; public static boolean hideOtherExchanges = false; public static boolean hideUpdateNotice = false; public BMapManager mBMapMan = null; public String mStrKey = "4BFEB7A7F3E7CD4B0FBAE61BABD11F1E11D7EAC8"; public static void delete(File paramFile) { if (paramFile.isFile()) { paramFile.delete(); } while (!paramFile.isDirectory()) { return; } File[] arrayOfFile = paramFile.listFiles(); if ((arrayOfFile == null) || (arrayOfFile.length == 0)) { paramFile.delete(); return; } for (int i = 0;; i++) { if (i >= arrayOfFile.length) { paramFile.delete(); return; } delete(arrayOfFile[i]); } } public boolean init() { this.mBMapMan = new BMapManager(this); return this.mBMapMan.init(this.mStrKey, new MyGeneralListener()); } public void onCreate() { app = this; if (init()) { this.mBMapMan.getLocationManager().setNotifyInternal(10, 5); } super.onCreate(); try { localBundle = getPackageManager().getApplicationInfo(getPackageName(), 128).metaData; str2 = localBundle.getString("UMENG_CHANNEL"); arrayOfString1 = localBundle.getString("HIDE_OTHER_EXCHANGE_APK_CHANNEL").split(","); i = 0; } catch (Exception localException1) { for (;;) { Bundle localBundle; String str2; String[] arrayOfString1; int i; String[] arrayOfString2; int j; Logger.w(localException1); continue; i++; continue; label303: if (arrayOfString2[j].equals(str2)) { hideUpdateNotice = true; } else { j++; } } } if (i >= arrayOfString1.length) {} for (;;) { arrayOfString2 = localBundle.getString("HIDE_DOUGUO_UPDATE_NOTICE").split(","); j = 0; int k = arrayOfString2.length; if (j < k) { break label303; } WeiboHelper.setConfig(app); RenrenHelper.setConfig(app); DouguoWebAPI.setConfig(app); Logger.setConfig(app); Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(getApplicationContext())); try { String str1 = Environment.getExternalStorageDirectory().getAbsolutePath() + "/douguo/" + getPackageName(); File localFile1 = new File(str1); File localFile2 = localFile1.getParentFile(); if (!localFile2.exists()) { localFile2.mkdir(); } if (!localFile1.exists()) { localFile1.mkdir(); } File localFile3 = new File(str1 + "/.nomedia"); if (!localFile3.exists()) { localFile3.createNewFile(); } return; } catch (Exception localException2) { Logger.w(localException2); } if (!arrayOfString1[i].equals(str2)) { break; } hideOtherExchanges = true; } } public void onLowMemory() { super.onLowMemory(); Logger.e("!!!!!!!!!!!!!!onLowMemory!!!!!!!!!!!!"); } public void onTerminate() { if (this.mBMapMan != null) { this.mBMapMan.destroy(); this.mBMapMan = null; } super.onTerminate(); new Thread() { public void run() { App.delete(new File(Environment.getExternalStorageDirectory() + "/douguo/yummyDiary/")); } }.start(); } static class MyGeneralListener implements MKGeneralListener { public void onGetNetworkState(int paramInt) { Toast.makeText(App.app.getApplicationContext(), "您的网络出错啦!", 1).show(); } public void onGetPermissionState(int paramInt) {} } } |
这个类有两个自定义的方法,一个是delete(File paramFile),用于删除指定文件,一个是
init(),用于初始化百度地图以及网络连接。进入onCreate()方法,首选是给变量app实例化。接着调用init()方法进行判断,如果在init()方法返回true,说明有网络连接正常并且已经初始化完毕百度地图,之后会不断发送tNotify通知。然后进入try
catch方法里面,由于反编译的问题,有些语句反编译完毕后就是现在这个样子。至于如何解读,以后会介绍,现在不是重点。看一下,在try里面是初始化了友盟的一些东西,然后再catch里面声明了一些变量,并且根据某些条件创建或者删除指定的文件。最后就是onTerminate()方法,可以看到在这个方法里面它销毁了百度地图、删除了一些程序的文件等。
3、app_3
import android.app.ActivityManager; import android.app.ActivityManager.RunningAppProcessInfo; import android.app.Application; import android.content.Context; import android.os.Process; import com.baidu.android.silentupdate.SilentManager; import java.util.Iterator; import java.util.List; public class FrontiaApplication extends Application { private static final String a =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYAFbG0oYmKgh6o7BhZIHf1njBpZXqyWBnYz2ip3Wp
+s97OeA/pTe8xebuGJHwq4xbsGQrJWepIbUVrdjm6JRmdvuJhar7/
hC/UNnUkJgYdYl10OZKlvcFFgK3V7XGBPplXldDnhbgscna3JG8U3025WSxZCP5vy/8cfxsEoVx5QIDAQAB"; public static void initFrontiaApplication(Context paramContext) { SilentManager.setKey
("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYAFbG0oYmKgh6o7BhZIHf1njBpZXqyWBnYz2ip3Wp+
s97OeA/pTe8xebuGJHwq4xbsGQrJWepIbUVrdjm6JRmdvuJhar7/
hC/UNnUkJgYdYl10OZKlvcFFgK3V7XGBPplXldDnhbgscna3JG8U3025WSxZCP5vy/8cfxsEoVx5QIDAQAB"); SilentManager.enableRSA(false); SilentManager.loadLib(paramContext.getApplicationContext(), "frontia_plugin", "plugin-deploy.jar"); } public void onCreate() { super.onCreate(); ActivityManager localActivityManager = (ActivityManager)getSystemService("activity"); int i = Process.myPid(); Iterator localIterator = localActivityManager.getRunningAppProcesses().iterator(); while (localIterator.hasNext()) { ActivityManager.RunningAppProcessInfo localRunningAppProcessInfo =
(ActivityManager.RunningAppProcessInfo)localIterator.next(); if ((localRunningAppProcessInfo.pid == i) &&
(!localRunningAppProcessInfo.processName.endsWith(getPackageName()))) { initFrontiaApplication(getApplicationContext()); } } } } import android.content.Context; import com.baidu.frontia.FrontiaApplication; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; public class UILApplication extends FrontiaApplication { public static void initImageLoader(Context paramContext) { ImageLoaderConfiguration localImageLoaderConfiguration =
new ImageLoaderConfiguration.Builder(paramContext).threadPriority(3).denyCacheImageMultipleSizesInMemory().
discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build(); ImageLoader.getInstance().init(localImageLoaderConfiguration); } public void onCreate() { com.nostra13.universalimageloader.utils.StorageUtils.basePath = "Meishi"; com.nostra13.universalimageloader.utils.StorageUtils.childPath = "Temp"; com.nostra13.universalimageloader.utils.StorageUtils.childImgName = "imgs"; super.onCreate(); CrashHandler.getInstance().init(this); initImageLoader(getApplicationContext()); } }
|
这个app的Application的实现比较特殊一点,使用了两个类,在第一个类的onCreate()方法里面主要是先是获取所有的进程,然后迭代进行判断,如果满足条件则调用initFrontiaApplication()方法用来设置key。第二个类则用于初始化universalimageloader。其实觉得没有必要分开来操作,写在一个Application类里面即可。
4、app_4
import android.app.Application;
import android.graphics.Bitmap.Config;
import android.text.TextUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import cn.jpush.android.api.BasicPushNotificationBuilder;
import cn.jpush.android.api.JPushInterface;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.DisplayImageOptions.Builder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration.Builder;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import java.util.Calendar;
import java.util.Date;
public class AzkApp
extends Application
{
public static final String BASEURL = Api.BASE_URL;
public static DisplayImageOptions avatarOptions;
public static DisplayImageOptions defaultOptions;
private static AzkApp instance;
private static boolean jpushInitied;
public static DisplayImageOptions noStubOptions;
private final String COOKIEURL = "http://aimeiwei.me";
public BDLocation bdLocation;
private CookieManager cookieManager;
private CookieSyncManager cookieSyncManager;
public BMapManager mBMapMan;
public LocationClient mLocationClient;
public int mapCount;
private String nickname = "";
private String password = "";
private String username = "";
private String getBaiduKey()
{
return AzkHelper.getMetaData(getApplicationContext(), "BAIDU_KEY");
}
public static AzkApp getInstance()
{
return instance;
}
private void initCookieManager()
{
this.cookieSyncManager = CookieSyncManager.createInstance(this);
this.cookieManager = CookieManager.getInstance();
this.cookieManager.setAcceptCookie(true);
if (isLogin())
{
String str = this.cookieManager.getCookie("http://aimeiwei.me");
if ((str == null) || (!str.contains("username")) || (!str.contains("password")))
{
AzkHelper.showLog("初始化cookie");
setCookie(this.username, this.password);
}
}
showCookie();
}
private void initHttp()
{
AzkHelper.showLog("httpClient初始化");
Http.initHttp(AzkHelper.sAzkUserAgent);
Http.setBaseUrl(Api.API_URL);
if ((!TextUtils.isEmpty(this.username)) && (!TextUtils.isEmpty(this.password))) {
Http.setUser(this.username, this.password);
}
}
private void initImageLoader()
{
AzkHelper.showLog("ImageLoader图片加载器初始化");
long l1 = Runtime.getRuntime().maxMemory();
long l2 = l1 / 1024L / 1024L;
AzkHelper.showLog("maxHeap: " + l2);
int i = (int)l1 / 4;
DisplayImageOptions.Builder localBuilder1 = new DisplayImageOptions.Builder();
DisplayImageOptions.Builder localBuilder2 = localBuilder1.showImageOnLoading(2130837835);
Bitmap.Config localConfig;
ImageScaleType localImageScaleType;
label103:
int j;
label188:
ImageLoaderConfiguration.Builder localBuilder6;
if (l2 >= 256L)
{
localConfig = Bitmap.Config.ARGB_8888;
DisplayImageOptions.Builder localBuilder3 = localBuilder2.bitmapConfig(localConfig);
if (l2 < 256L) {
break label283;
}
localImageScaleType = ImageScaleType.IN_SAMPLE_POWER_OF_2;
localBuilder3.imageScaleType(localImageScaleType).cacheInMemory(true).cacheOnDisc(true);
defaultOptions = localBuilder1.build();
DisplayImageOptions.Builder localBuilder4 = new DisplayImageOptions.Builder();
localBuilder4.cacheInMemory(true).cacheOnDisc(true);
noStubOptions = localBuilder4.build();
ImageLoaderConfiguration.Builder localBuilder5 =
new ImageLoaderConfiguration.Builder(getApplicationContext()).
memoryCacheExtraOptions(Constants.IMAGE_SIZE, Constants.IMAGE_SIZE);
if (l2 < 256L) {
break label291;
}
j = 1;
localBuilder6 = localBuilder5.threadPriority(5 - j);
if (l2 < 256L) {
break label297;
}
}
label283:
label291:
label297:
for (int k = 3;; k = 2)
{
ImageLoaderConfiguration localImageLoaderConfiguration =
localBuilder6.threadPoolSize(k).memoryCacheSize(i).memoryCache(new WeakMemoryCache()).
denyCacheImageMultipleSizesInMemory().defaultDisplayImageOptions(defaultOptions).build();
ImageLoader.getInstance().init(localImageLoaderConfiguration);
avatarOptions = localBuilder1.displayer(new RoundedBitmapDisplayer(8)).build();
return;
localConfig = Bitmap.Config.RGB_565;
break;
localImageScaleType = ImageScaleType.IN_SAMPLE_INT;
break label103;
j = 2;
break label188;
}
}
private void removeCookie()
{
this.cookieManager.removeSessionCookie();
this.cookieManager.removeAllCookie();
this.cookieSyncManager.sync();
}
private void setCookie(String paramString1, String paramString2)
{
Calendar localCalendar = Calendar.getInstance();
localCalendar.set(2025, 11, 29);
String str = localCalendar.getTime().toString();
this.cookieManager.setCookie("http://aimeiwei.me", "username=" + paramString1 + "; path=/; expires=" + str);
this.cookieManager.setCookie("http://aimeiwei.me", "password=" + paramString2 + "; path=/; expires=" + str);
this.cookieSyncManager.sync();
showCookie();
}
private void setJpushAlias()
{
AzkHelper.showLog("jpush", "username: " + this.username);
JPushInterface.setAliasAndTags(this, this.username, null);
}
private void showCookie()
{
String str = this.cookieManager.getCookie("http://aimeiwei.me");
AzkHelper.showLog("cookie:" + str);
}
public String getNickname()
{
return this.nickname;
}
public String getPassword()
{
return this.password;
}
public String getUsername()
{
return this.username;
}
public void initBMapManager()
{
if (this.mBMapMan == null)
{
this.mBMapMan = new BMapManager(this);
String str = getBaiduKey();
AzkHelper.showLog("初始化BMapManager, BAIDU_KEY: " + str);
this.mBMapMan.init(str, new MKGeneralListener()
{
public void onGetNetworkState(int paramAnonymousInt)
{
if (paramAnonymousInt == 2) {
AzkHelper.showErrorLog("您的网络出错啦!");
}
}
public void onGetPermissionState(int paramAnonymousInt)
{
if (paramAnonymousInt == 300) {
AzkHelper.showLog("请输入正确的百度授权Key");
}
}
});
}
}
public void initJpush()
{
if (jpushInitied) {
return;
}
AzkHelper.showLog("极光推送初始化");
AzkHelper.showLog("jpush", "极光推送初始化");
JPushInterface.init(this);
BasicPushNotificationBuilder localBasicPushNotificationBuilder = new BasicPushNotificationBuilder(this);
localBasicPushNotificationBuilder.statusBarDrawable = 2130837777;
JPushInterface.setPushNotificationBuilder(Integer.valueOf(1), localBasicPushNotificationBuilder);
if (!TextUtils.isEmpty(this.username)) {
setJpushAlias();
}
jpushInitied = true;
}
public void initMap()
{
AzkHelper.showLog("百度地图初始化");
this.mLocationClient = new LocationClient(this);
LocationClientOption localLocationClientOption = new LocationClientOption();
localLocationClientOption.setProdName(getString(2131296262));
localLocationClientOption.setOpenGps(true);
localLocationClientOption.setPriority(2);
localLocationClientOption.setAddrType("all");
localLocationClientOption.setCoorType("gcj02");
this.mLocationClient.setLocOption(localLocationClientOption);
this.mLocationClient.setAK(getBaiduKey());
initBMapManager();
}
public boolean isLogin()
{
boolean bool = true;
if ((TextUtils.isEmpty(this.username)) || (TextUtils.isEmpty(this.password))) {
bool = false;
}
return bool;
}
public boolean isYourself(User paramUser)
{
if ((TextUtils.isEmpty(this.username)) || (paramUser == null)) {
return false;
}
return this.username.equals(paramUser.getId());
}
public boolean isYourself(UserNew paramUserNew)
{
if ((TextUtils.isEmpty(this.username)) || (paramUserNew == null)) {
return false;
}
return this.username.equals(paramUserNew.getId());
}
public void onCreate()
{
AzkHelper.showLog("Application Aimeiwei onCreate");
super.onCreate();
instance = this;
AzkHelper.prepareUserAgent(this);
this.username = AzkHelper.getStringPref(this, "username");
this.password = AzkHelper.getStringPref(this, "password");
this.nickname = AzkHelper.getStringPref(this, "nickname");
AzkHelper.showLog("BuildConfig.DEBUG: false");
AzkHelper.closeLog();
initHttp();
initImageLoader();
initJpush();
initMap();
initCookieManager();
}
public void onLowMemory()
{
AzkHelper.showLog("onLowMemory");
super.onLowMemory();
}
public void onTerminate()
{
instance = null;
if (this.mBMapMan != null)
{
this.mBMapMan.destroy();
this.mBMapMan = null;
}
super.onTerminate();
}
public void removeUser()
{
Http.clearUser();
AzkHelper.removePref(this, "username");
AzkHelper.removePref(this, "password");
AzkHelper.removePref(this, "nickname");
this.username = "";
this.password = "";
this.nickname = "";
AccessTokenKeeper.clear(getApplicationContext());
removeCookie();
}
public void removeUser2()
{
Http.clearUser();
AzkHelper.removePref(this, "username");
AzkHelper.removePref(this, "password");
AzkHelper.removePref(this, "nickname");
this.password = "";
this.nickname = "";
AccessTokenKeeper.clear(getApplicationContext());
AccessTokenKeeperForQQ.clear(getApplicationContext());
removeCookie();
}
public void setNickname(String paramString)
{
AzkHelper.setStringPref(this, "nickname", paramString);
this.nickname = paramString;
}
public void setPassword(String paramString)
{
AzkHelper.setStringPref(this, "password", paramString);
this.password = paramString;
}
public void setUser(String paramString1, String paramString2)
{
setUserName(paramString1);
setPassword(paramString2);
Http.setUser(paramString1, paramString2);
}
public void setUser(String paramString1, String paramString2, String paramString3)
{
setNickname(paramString3);
setUser(paramString1, paramString2);
setCookie(paramString1, paramString2);
}
public void setUserName(String paramString)
{
AzkHelper.setStringPref(this, "username", paramString);
this.username = paramString;
setJpushAlias();
}
} |
这个app的实现相对来说还是比较复杂的,但是无非就是初始化一些信息。从import导包可以看到,使用了极光推送、百度地图以及universalimageloader,所以按照之前的分析经验之后一定会在onCreate()方法里面去初始化这些功能的。看一下onCreate()方法:
public void onCreate() { AzkHelper.showLog("Application Aimeiwei onCreate"); super.onCreate(); instance = this; AzkHelper.prepareUserAgent(this); this.username = AzkHelper.getStringPref(this, "username"); this.password = AzkHelper.getStringPref(this, "password"); this.nickname = AzkHelper.getStringPref(this, "nickname"); AzkHelper.showLog("BuildConfig.DEBUG: false"); AzkHelper.closeLog(); initHttp(); initImageLoader(); initJpush(); initMap(); initCookieManager(); } |
很清晰明了,从方法名称也可以看出来,就是初始化各种功能。至于具体方法的实现,不多做介绍,感兴趣可以自己去研究。
最后总结一下,上面例举了四个市场上的app程序的Application类的实现。从中可以发现,在Application类的实现类中,无非就是做一些初始化程序数据、检查运行环境、销毁数据等。
1、初始化程序数据:
常用的初始化的手段有创建程序所需要的目录,设置开发平台的key,初始化地图信息,初始化http或者其他和网络有关的东西,初始化推送等等。
2、检查运行环境
比如检查是否存在sd卡、判断网络连接状况、检查内存等等。
3、销毁数据
就是在onTerminate()方法里面销毁之前使用到的一些东西。说到onTerminate()这个方法,在官方文档中是这样说的,
This method is for use in emulated process environments.
It will never be called on a production Android device,
where processes are removed by simply killing them;
no user code (including this callback) is executed when
doing so.
它是在模拟环境下调用的,在真机中永远不会被调用。那为什么那么多app的Application类都用到这个方法呢?下面写一个demo测试一下,看结果如何。
首先在真机测试,代码:
import android.app.Application; public class APP extends Application{ @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); System. out.println("onCreate()" ); } @Override public void onLowMemory() { // TODO Auto-generated method stub super.onLowMemory(); System. out.println("onCreate()" ); } @Override public void onTerminate() { // TODO Auto-generated method stub super.onTerminate(); System. out.println("onCreate()" ); } }
|
结果:
打开程序的时候调用了ocCreate()方法,这个没有问题,下面退出程序看看。我直接按返回家退出,发现并没有调用onTerminate()方法。接下来使用模拟器看看结果如何:
运行程序,发现调用了ocCreate()方法,
退出程序看看,发现也没有调用。所以感觉onTerminate()这个方法还是不要使用为好,官方既然说了不会再真机中调用,那么应该不会有错。所以在很多app里面使用到了这个方法,有点不明觉厉,明白的朋友可以交流一下。
|