Java tutorial
/** * Copyright 2016 bingoogolapple * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package cn.bingoogolapple.scaffolding.util; import android.app.Activity; import android.app.ActivityManager; import android.app.Application; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.net.ConnectivityManager; import android.os.Build; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import com.orhanobut.logger.AndroidLogAdapter; import com.orhanobut.logger.Logger; import com.orhanobut.logger.PrettyFormatStrategy; import java.util.Iterator; import java.util.Stack; import cn.bingoogolapple.scaffolding.R; import cn.bingoogolapple.scaffolding.net.ApiException; import static android.content.Context.ACTIVITY_SERVICE; /** * : :bingoogolapple@gmail.com * :16/3/21 ?1:25 * ??: */ public class AppManager implements Application.ActivityLifecycleCallbacks { private static final AppManager sInstance; private static final Application sApp; private int mActivityStartedCount = 0; private long mLastPressBackKeyTime; private Stack<Activity> mActivityStack = new Stack<>(); private boolean mIsBuildDebug; private Delegate mDelegate; static { Application app = null; try { app = (Application) Class.forName("android.app.AppGlobals").getMethod("getInitialApplication") .invoke(null); if (app == null) throw new IllegalStateException("Static initialization of Applications must be on main thread."); } catch (final Exception e) { Log.e(AppManager.class.getSimpleName(), "Failed to get current application from AppGlobals." + e.getMessage()); try { app = (Application) Class.forName("android.app.ActivityThread").getMethod("currentApplication") .invoke(null); } catch (final Exception ex) { Log.e(AppManager.class.getSimpleName(), "Failed to get current application from ActivityThread." + e.getMessage()); } } finally { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) { try { Class.forName("android.os.AsyncTask"); } catch (ClassNotFoundException e) { } } sApp = app; sInstance = new AppManager(); sApp.registerActivityLifecycleCallbacks(sInstance); } } private AppManager() { // ? CrashHandler.getInstance().init(); sApp.registerReceiver(new BroadcastReceiver() { private boolean mIsFirstReceiveBroadcast = true; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) { if (!mIsFirstReceiveBroadcast) { try { if (NetUtil.isNetworkAvailable()) { RxBus.send(new RxEvent.NetworkConnectedEvent()); } else { RxBus.send(new RxEvent.NetworkDisconnectedEvent()); } } catch (Exception e) { } } else { mIsFirstReceiveBroadcast = false; } } } }, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } /** * Application onCreate * * @param buildType BuildConfig.BUILD_TYPE * @param delegate ? */ public void init(String buildType, Delegate delegate) { mIsBuildDebug = StringUtil.isEqual(buildType, "debug"); mDelegate = delegate; // ?? Logger.addLogAdapter(new AndroidLogAdapter(PrettyFormatStrategy.newBuilder().methodCount(1).build()) { @Override public boolean isLoggable(int priority, String tag) { return mIsBuildDebug; } }); } public static AppManager getInstance() { return sInstance; } public static Application getApp() { return sApp; } /** * ? debug * * @return */ public boolean isBuildDebug() { return mIsBuildDebug; } /** * LeakCanary Fragment * * @param fragment */ public void refWatcherWatchFragment(Fragment fragment) { if (mDelegate != null) { mDelegate.refWatcherWatchFragment(fragment); } } /** * Activity ??? Fragment??????? Activity Fragment * * @param activity * @return */ public boolean isActivityNotContainFragment(Activity activity) { if (mDelegate != null) { return !mDelegate.isActivityContainFragment(activity); } // true Activity ?? Fragment return true; } /** * ? * * @param apiException */ public void handleServerException(ApiException apiException) { if (mDelegate != null) { mDelegate.handleServerException(apiException); } } @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) { mActivityStack.add(activity); } @Override public void onActivityStarted(Activity activity) { if (mActivityStartedCount == 0) { RxBus.send(new RxEvent.AppEnterForegroundEvent()); } mActivityStartedCount++; } @Override public void onActivityResumed(Activity activity) { UMAnalyticsUtil.onActivityResumed(activity); } @Override public void onActivityPaused(Activity activity) { UMAnalyticsUtil.onActivityPaused(activity); } @Override public void onActivityStopped(Activity activity) { mActivityStartedCount--; if (mActivityStartedCount == 0) { RxBus.send(new RxEvent.AppEnterBackgroundEvent()); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) { } @Override public void onActivityDestroyed(Activity activity) { mActivityStack.remove(activity); } /** * Activity? * * @return */ public boolean isActivityStackEmpty() { return mActivityStack.isEmpty(); } /** * ActivityActivity * * @return */ public int getActivityStackSize() { return mActivityStack.size(); } /** * ??Activity * * @return */ public Activity currentActivity() { Activity activity = null; if (!mActivityStack.empty()) { activity = mActivityStack.lastElement(); } return activity; } /** * Activity * * @param activity */ public void popOneActivity(Activity activity) { if (activity == null || mActivityStack.isEmpty()) { return; } if (!activity.isFinishing()) { activity.finish(); } mActivityStack.remove(activity); } /** * ? MainActivity ? * * @param activityClass */ public void popOthersActivity(Class<Activity> activityClass) { if (activityClass == null || mActivityStack.isEmpty()) { return; } Iterator<Activity> iterator = mActivityStack.iterator(); while (iterator.hasNext()) { Activity activity = iterator.next(); if (!activity.getClass().equals(activityClass)) { activity.finish(); iterator.remove(); } } } /** * ?? ? */ public void exitWithDoubleClick() { if (System.currentTimeMillis() - mLastPressBackKeyTime <= 1500) { exit(); } else { mLastPressBackKeyTime = System.currentTimeMillis(); ToastUtil.show(R.string.toast_exit_tip); } } /** * Activity */ public void finishAllActivity() { try { while (true) { Activity activity = currentActivity(); if (activity == null) { break; } popOneActivity(activity); } } catch (Exception e) { Logger.e("Activity"); } } /** * ? */ public void exit() { try { finishAllActivity(); // ?Process.killSystem.exit??MobclickAgent.onKillProcess(Context context)??? UMAnalyticsUtil.onKillProcess(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); } catch (Exception e) { Logger.e(""); } } /** * ??? * * @return */ public boolean isBackStage() { return mActivityStartedCount == 0; } /** * ??? * * @return */ public boolean isFrontStage() { return mActivityStartedCount > 0; } /** * ??? * * @return */ public static String getAppName() { try { return sApp.getPackageManager().getPackageInfo(sApp.getPackageName(), 0).applicationInfo .loadLabel(sApp.getPackageManager()).toString(); } catch (Exception e) { // api getPackageName()????? return ""; } } /** * ???? * * @return */ public static String getCurrentVersionName() { try { return sApp.getPackageManager().getPackageInfo(sApp.getPackageName(), 0).versionName; } catch (Exception e) { // api getPackageName()????? return ""; } } /** * ??? * * @return */ public static int getCurrentVersionCode() { try { return sApp.getPackageManager().getPackageInfo(sApp.getPackageName(), 0).versionCode; } catch (Exception e) { // api getPackageName()????? return 0; } } /** * ??? * * @return */ private static String getChannel() { try { ApplicationInfo appInfo = sApp.getPackageManager().getApplicationInfo(sApp.getPackageName(), PackageManager.GET_META_DATA); return appInfo.metaData.getString("UMENG_CHANNEL"); } catch (Exception e) { return ""; } } public static boolean isInOtherProcess(Context context) { String processName = null; ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE); Iterator iterator = am.getRunningAppProcesses().iterator(); while (iterator.hasNext()) { ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (iterator.next()); try { if (info.pid == android.os.Process.myPid()) { processName = info.processName; } } catch (Exception e) { Log.d(AppManager.class.getSimpleName(), "Error>> :" + e.toString()); } } return processName == null || !processName.equalsIgnoreCase(context.getPackageName()); } public interface Delegate { /** * LeakCanary Fragment * * @param fragment */ void refWatcherWatchFragment(Fragment fragment); /** * Activity ?? Fragment??????? Activity Fragment * * @param activity * @return */ boolean isActivityContainFragment(Activity activity); /** * ? * * @param apiException */ void handleServerException(ApiException apiException); } }