如何在代码中检测我处于发布模式还是调试模式?
试试下面的方法:
boolean isDebuggable = ( 0 != ( getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE ) );
科特林:
val isDebuggable = 0 != applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
这是从这里的邦德尔邮局拍下来的
最简单、最好的长期解决方案是使用BuildConfig.DEBUG。这是一个布尔值,调试版本为真,否则为假:
if (BuildConfig.DEBUG) {
// do something for a debug build
}
有报道说,这个值在基于eclipse的构建中不是100%可靠的,尽管我个人没有遇到过问题,所以我不能说它到底有多大的问题。
如果你正在使用Android Studio,或者如果你在命令行中使用Gradle,你可以在BuildConfig中添加你自己的东西,或者调整调试和发布构建类型,以帮助在运行时区分这些情况。
The solution from Illegal Argument is based on the value of the android:debuggable flag in the manifest. If that is how you wish to distinguish a "debug" build from a "release" build, then by definition, that's the best solution. However, bear in mind that going forward, the debuggable flag is really an independent concept from what Gradle/Android Studio consider a "debug" build to be. Any build type can elect to set the debuggable flag to whatever value that makes sense for that developer and for that build type.
由于关于BuildConfig的混合评论。调试,我使用以下方法在调试模式下禁用崩溃分析(和分析):
更新/ app / build.gradle
android {
compileSdkVersion 25
buildToolsVersion "25.0.1"
defaultConfig {
applicationId "your.awesome.app"
minSdkVersion 16
targetSdkVersion 25
versionCode 100
versionName "1.0.0"
buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'true'
}
buildTypes {
debug {
debuggable true
minifyEnabled false
buildConfigField 'boolean', 'ENABLE_CRASHLYTICS', 'false'
}
release {
debuggable false
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
然后,在代码中检测ENABLE_CRASHLYTICS标志,如下所示:
if (BuildConfig.ENABLE_CRASHLYTICS)
{
// enable crashlytics and answers (Crashlytics by default includes Answers)
Fabric.with(this, new Crashlytics());
}
在你的应用中使用相同的概念,并将ENABLE_CRASHLYTICS重命名为任何你想要的。我喜欢这种方法,因为我可以在配置中看到标志,并且可以控制标志。
是的,你将没有问题使用:
if (BuildConfig.DEBUG) {
//It's not a release version.
}
除非您导入了错误的BuildConfig类。确保您引用的是项目的BuildConfig类,而不是来自任何依赖库。
或者,您可以使用BuildConfig.BUILD_TYPE进行区分;
如果您正在运行调试构建 BuildConfig.BUILD_TYPE.equals(“调试”);返回true。对于发布,构建BuildConfig.BUILD_TYPE.equals("release");返回true。
我正在使用这种解决方案,以防发现我的应用程序正在调试版本上运行。
if (BuildConfig.BUILD_TYPE.equals("debug")){
//Do something
}
确保您导入了正确的BuildConfig类 是的,你将没有问题使用:
if (BuildConfig.DEBUG) {
//It's not a release version.
}
推荐文章
- BottomSheetDialogFragment的圆角
- 在应用程序启动时出现“无法获得BatchedBridge,请确保您的bundle被正确打包”的错误
- 我如何改变默认对话框按钮的文本颜色在安卓5
- 更改单选按钮的圆圈颜色
- 如何在android中复制一个文件?
- adb找不到我的设备/手机(MacOS X)
- 如何在新的材质主题中改变背面箭头的颜色?
- androidviewpager与底部点
- 相同的导航抽屉在不同的活动
- 如何从视图中获得托管活动?
- 单一的TextView与多种颜色的文本
- 如何在非活动类(LocationManager)中使用getSystemService ?
- 在清单中注册应用程序类?
- Android:从数组中编程创建旋转器
- Android命令行工具sdkmanager总是显示:警告:无法创建设置