Android 实例解说Application类
版本:1.0
日期:2014.3.28
版权:© 2014 kince 转载注明出处何为Application,有何用途?Google官方文档是这样说的:维护全局应用程序的状态,使用的时候继承于它创建一个子类即可,同时在AndroidManifest.xml文件的<application> 标签的name属性制定它的名字,也就是子类名称。当应用程序的包被创建的时候这个类就会被实例化,而且它的生命周期和应用程序是一样的。不过Google在下面的提示中也说道大多数情况下不需要使用这个类,因为如果应用程序使用了单例模式的话,效果和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系统内存低的情况下调用的,可以在这个方法里面做一下释放内存的功能。
this.httpClient = createHttpClient(); System.out.println(Build.VERSION.SDK_INT); initImageLoader(getApplicationContext());
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) {} } }
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()); } }
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(); }很清晰明了,从方法名称也可以看出来,就是初始化各种功能。至于具体方法的实现,不多做介绍,感兴趣可以自己去研究。
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()" ); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。