DebugApplication

2018-05-03  本文已影响0人  echochen9988

在AndroidStudio中我们可以把一些只有在debug包下生效的代码不引入到release版本中,比如接入LeakCanary,下面是一个demo

包结构

image.png

关键类

build.gradle只引入LeakCanary的debug版本

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:27.0.2'
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.5.4'

}

主包的Application类

public class AppDemoApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        debugConfig();
    }

    /**
     * 只在debug包下生效的配置
     */
    protected void debugConfig() {
        Toast.makeText(this, " AppDemoApplication debugConfig", Toast.LENGTH_LONG).show();
    }
}

debug包的Application类

public class AppDemoDebugApplication extends AppDemoApplication {
    private static final String TAG = "AppDemoDebugApplication";

    @Override
    protected void debugConfig() {
        super.debugConfig();
        if (LeakCanary.isInAnalyzerProcess(this)) {
            // This process is dedicated to LeakCanary for heap analysis.
            // You should not init your app in this process.
            return;
        }
        LeakCanary.install(this);
        Toast.makeText(this, " LeakCanary.install", Toast.LENGTH_LONG).show();
    }
}

debug包的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.netease.wm.appdemo">

    <application
        xmlns:tools="http://schemas.android.com/tools"
        tools:replace="android:name"
        android:name=".app.AppDemoDebugApplication">
    </application>

</manifest>
上一篇下一篇

猜你喜欢

热点阅读