日常开发的时候,adb端口经常被一些其他程序占用,譬如一些手机助手软件会频繁的导致5037端口不可用,其实我们可以自定义adb的端口,而且一劳永逸,不用在频繁的 adb kill-server的命令 或者查找占用端口的进程去杀掉,这也太麻烦。
- win系统配置ANDROID_ADB_SERVER_PORT
在系统环境变量中定义 ANDROID_ADB_SERVER_PORT 的值即可,这样adb在运行的时候回使用我们配置的ANDROID_ADB_SERVER_PORT值,而不是原来默认的5037这个端口,
- 配置ANDROID_ADB_SERVER_PORT作用
大家好奇为啥通过配置ANDROID_ADB_SERVER_PORT就可以修改adb的端口,看看adb的源码
private static final String SERVER_PORT_ENV_VAR = "ANDROID_ADB_SERVER_PORT"; //$NON-NLS-1$
// Where to find the ADB bridge.
static final String DEFAULT_ADB_HOST = "127.0.0.1"; //$NON-NLS-1$
static final int DEFAULT_ADB_PORT = 5037;//默认端口
/**
* Returns the port where adb server should be launched. This looks at:
* <ol>
* <li>The system property ANDROID_ADB_SERVER_PORT</li>
* <li>The environment variable ANDROID_ADB_SERVER_PORT</li>
* <li>Defaults to {@link #DEFAULT_ADB_PORT} if neither the system property nor the env var
* are set.</li>
* </ol>
*
* @return The port number where the host's adb should be expected or started.
*/
private static int getAdbServerPort() {
// check system property
Integer prop = Integer.getInteger(SERVER_PORT_ENV_VAR);
if (prop != null) {
try {
return validateAdbServerPort(prop.toString());
} catch (IllegalArgumentException e) {
String msg = String.format(
"Invalid value (%1$s) for ANDROID_ADB_SERVER_PORT system property.",
prop);
Log.w(DDMS, msg);
}
}
// when system property is not set or is invalid, parse environment property
try {
String env = System.getenv(SERVER_PORT_ENV_VAR);
if (env != null) {
return validateAdbServerPort(env);
}
} catch (SecurityException ex) {
// A security manager has been installed that doesn't allow access to env vars.
// So an environment variable might have been set, but we can't tell.
// Let's log a warning and continue with ADB's default port.
// The issue is that adb would be started (by the forked process having access
// to the env vars) on the desired port, but within this process, we can't figure out
// what that port is. However, a security manager not granting access to env vars
// but allowing to fork is a rare and interesting configuration, so the right
// thing seems to be to continue using the default port, as forking is likely to
// fail later on in the scenario of the security manager.
Log.w(DDMS,
"No access to env variables allowed by current security manager. "
+ "If you've set ANDROID_ADB_SERVER_PORT: it's being ignored.");
} catch (IllegalArgumentException e) {
String msg = String.format(
"Invalid value (%1$s) for ANDROID_ADB_SERVER_PORT environment variable (%2$s).",
prop, e.getMessage());
Log.w(DDMS, msg);
}
// use default port if neither are set
return DEFAULT_ADB_PORT;
}
复制代码
上面的只是截取了主要获取端口号的方法getAdbServerPort(),该方法首先获取操作系统属性ANDROID_ADB_SERVER_PORT配置的值,如果找到就返回,否则才会返回默认的值DEFAULT_ADB_PORT,也是5037这个端口,所有我们通过配置ANDROID_ADB_SERVER_PORT是可以修改adb端口的目的
如果配置完ANDROID_ADB_SERVER_PORT该属性,检测不到设备的话,重启一下电脑就好