【Android】自动判断调试环境决定是否打印日志

【关键词】

日志 调试环境

【问题】
  • 打包后,忘记了设置LogUtil. DEBUG_MODE = false;,导致日志还可见,有没有什么办法自动判断运行环境来决定是否打印日志?
【解决方案】
  • eclipse特性:直接通过 eclipse 运行的时候,其 debug 属性为 true, 通过 eclipse 的导出功能打包时,其 debug 为 false;
  • 使用 LogUtil. isApkDebugable()方法需要传入上下文,可以通过继承 Application 并配置 Manifest来实现;
【代码】

配置Manifest

 
  
android:name="com.example.loutest.LouApp"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
android:name=".MainActivity"
android:label="@string/app_name" >
android:name="android.intent.action.MAIN" />
 
android:name="android.intent.category.LAUNCHER" />

Application

 
  
public class LouApp extends Application {
 
public static boolean DEBUG;
 
@Override
public void onCreate() {
// 根据 context 判断debugable
DEBUG = ToolUtil.isApkDebugable(this);
 
super.onCreate();
}
}

日志帮助类

 
  
public class LogUtil {
 
// private static final boolean DEBUG_MODE = true; // 之前是手动配置;
private static final boolean DEBUG_MODE = LouApp.DEBUG; // 现在是自动判断;
private static final String TAG = "Lou";
 
public static void d(String tag, String msg){if(DEBUG_MODE){Log.d(tag, msg);}}
public static void e(String tag, String msg){if(DEBUG_MODE){Log.e(tag, msg);}}
public static void i(String tag, String msg){if(DEBUG_MODE){Log.i(tag, msg);}}
public static void v(String tag, String msg){if(DEBUG_MODE){Log.v(tag, msg);}}
public static void w(String tag, String msg){if(DEBUG_MODE){Log.w(tag, msg);}}
 
public static void d(String msg){ d(TAG,msg);}
public static void e(String msg){ e(TAG,msg);}
public static void i(String msg){ i(TAG,msg);}
public static void v(String msg){ v(TAG,msg);}
public static void w(String msg){ w(TAG,msg);}
}

判断Apk是否是Debugable

 
  
public class ToolUtil {
public static boolean isApkDebugable(Context context) {
try {
ApplicationInfo info = context.getApplicationInfo();
return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception e) {
 
}
return false;
}
 
public static boolean isApkDebugable(Context context, String packageName) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(packageName, 1);
ApplicationInfo info = packageInfo.applicationInfo;
return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception e) {
 
}
return false;
}
}
【参考资料】

《Android应用程序的debug属性》


你可能感兴趣的:(Android)