本文主要是介绍LeakCanary测试app内存泄露+registerActivityLifecycleCallbacks管理Activity的生命周期,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
public class MyApplication extends Application {private String tag = "MyApplication";private static Stack<Activity> activityStack;//检测内存泄露private RefWatcher refWatcher;@Overridepublic void onCreate() {super.onCreate();//检测内存泄露if (LeakCanary.isInAnalyzerProcess(this)) {return;}refWatcher = LeakCanary.install(this);if (activityStack == null) {activityStack = new Stack<>();}addActivityLifeCallBack();}private void addActivityLifeCallBack() {registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {@Overridepublic void onActivityCreated(Activity activity, Bundle savedInstanceState) {Log.i(tag, "----------------onActivityCreated-----------------" + activity.toString());activityStack.add(activity);Log.i(tag, "onActivityCreated->activityStack:" + activityStack.size());refWatcher.watch(activity);}@Overridepublic void onActivityStarted(Activity activity) {Log.i(tag, "----------------onActivityStarted-----------------" + activity.toString());}@Overridepublic void onActivitySaveInstanceState(Activity activity, Bundle outState) {Log.i(tag, "----------------onActivitySaveInstanceState-----------------" + activity.toString());}@Overridepublic void onActivityResumed(Activity activity) {Log.i(tag, "----------------onActivityResumed-----------------" + activity.toString());}@Overridepublic void onActivityPaused(Activity activity) {Log.i(tag, "----------------onActivityPaused-----------------" + activity.toString());}@Overridepublic void onActivityStopped(Activity activity) {Log.i(tag, "----------------onActivityStopped-----------------" + activity.toString());}@Overridepublic void onActivityDestroyed(Activity activity) {Log.i(tag, "----------------onActivityDestroyed-----------------" + activity.toString());activityStack.remove(activity);Log.i(tag, "onActivityDestroyed->activityStack:" + activityStack.size());}});}/*** 关闭所有的Activity*/public void finishAll() {Log.i(tag, "----------------finishAll-----------------" + activityStack.size());for (int i = 0; i < activityStack.size(); i++) {if (null != activityStack.get(i)) {activityStack.get(i).finish();}}activityStack.clear();}/*** 获取当前的activity 的名字*/public String getCurrentActivityName(Activity activity) {String contextString = activity.toString();return contextString.substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));}/*** 获取当前的activity*/public Activity getCurrentActivity() {Log.i(tag, "----------------getCurrentActivity-----------------" + activityStack.size());if (activityStack.size() > 0) {Log.i(tag, "getCurrentActivity!=NULL");return activityStack.lastElement();} else {Log.i(tag, "getCurrentActivity==NULL");return null;}}
这篇关于LeakCanary测试app内存泄露+registerActivityLifecycleCallbacks管理Activity的生命周期的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!