1、判断要是BuildConfig.DEBUG为false,但AndroidManifest却声明为debuggable,可认为是被动态调试调试状态,强制退出
2、定时轮询,判断在BuildConfig.DEBUG为false时,是否有调试器连接,如果有,可认为是被动态调试调试状态,强制退出
3、定时轮询,判断在BuildConfig.DEBUG为false时,是否被其他进程用Ptrace方式跟踪,如果有,可认为是被动态调试调试状态,强制退出
public class DebuggerUtils {
/**
* 判断当前应用是否是debug状态
*/
public static boolean isDebuggable(Context context) {
try {
ApplicationInfo info = context.getApplicationInfo();
return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception e) {
return false;
}
}
/**
* 检测是否在非Debug编译模式下,进行了调试操作,以防动态调试
*
* @param context
* @return
*/
public static void checkDebuggableInNotDebugModel(Context context) {
//非Debug 编译,反调试检测
if (!BuildConfig.DEBUG) {
if (isDebuggable(context)) {
System.exit(0);
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
//每隔300ms检测一次
Thread.sleep(300);
//判断是否有调试器连接,是就退出
if (Debug.isDebuggerConnected()) {
System.exit(0);
}
//判断是否被其他进程跟踪,是就退出
if (isUnderTraced()) {
System.exit(0);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "SafeGuardThread");
t.start();
}
if (isUnderTraced()) {
System.exit(0);
}
}
/**
* 当我们使用Ptrace方式跟踪一个进程时,目标进程会记录自己被谁跟踪,可以查看/proc/pid/status看到这个信息,而没有被调试的时候TracerPid为0
*
* @return
*/
private static boolean isUnderTraced() {
String processStatusFilePath = String.format(Locale.US, "/proc/%d/status", android.os.Process.myPid());
File procInfoFile = new File(processStatusFilePath);
try {
BufferedReader b = new BufferedReader(new FileReader(procInfoFile));
String readLine;
while ((readLine = b.readLine()) != null) {
if (readLine.contains("TracerPid")) {
String[] arrays = readLine.split(":");
if (arrays.length == 2) {
int tracerPid = Integer.parseInt(arrays[1].trim());
if (tracerPid != 0) {
return true;
}
}
}
}
b.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}