平常開發的時候,adb端口常常被一些其餘程序佔用,譬如一些手機助手軟件會頻繁的致使5037端口不可用,其實咱們能夠自定義adb的端口,並且一勞永逸,不用在頻繁的 adb kill-server的命令 或者查找佔用端口的進程去殺掉,這也太麻煩。java
在系統環境變量中定義 ANDROID_ADB_SERVER_PORT 的值便可,這樣adb在運行的時候回使用咱們配置的ANDROID_ADB_SERVER_PORT值,而不是原來默認的5037這個端口,android
你們好奇爲啥經過配置ANDROID_ADB_SERVER_PORT就能夠修改adb的端口,看看adb的源碼bash
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端口的目的ui
若是配置完ANDROID_ADB_SERVER_PORT該屬性,檢測不到設備的話,重啓一下電腦就好this
完整源碼鏈接google