Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java代码自动打开Android USB调试模式

Android 通过代码打开USB调试模式

在相关代码流程里添加下列代码:

Settings.Secure.putInt(getContentResolver(), Settings.Global.ADB_ENABLED, 1);

即可自动打开USB调试模式(需要系统签名)

如果需要检测USB调试模式的开启状态,可通过下述代码检测:

boolean enableAdb = (Settings.Secure.getInt(getContentResolver(), Settings.Global.ADB_ENABLED, 0) > 0);

当然,还需要在AndroidManifest.xml中申请相关权限:

<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />

注意: 如果要使用WRITE_SECURE_SETTINGS权限,则需要系统级别的签名,或者能够把apk安装到/system/app中,但是如果不越狱一般没办法安装到该目录。


系统签名流程(基于Android Studio)

  1. 在Android Studio依次点击Build -> Generate Signed APK -> Create New 创建签名(如果已经创建过,则无需执行该步骤)

  2. 下载keytool-importkeypair对jks文件引入系统签名,下载地址为:https://github.com/getfatday/keytool-importkeypair

下载后,需要给该文件可执行权限,执行linux命令:chmod +x keytool-importkeypair即可

  1. 下载安卓系统签名:https://android.googlesource.com/platform/build/+/donut-release/target/product/security 这里我们只需要platform.pk8platform.x509.pem

  2. 都下载完成后,需要再linux系统中执行keytool-importkeypair,执行下列命令:

./keytool-importkeypair -k [jks文件名] -p [jks的密码] -pk8 platform.pk8 -cert platform.x509.pem -alias [jks的别名]
  1. 执行步骤4后会自动更新jks文件,回到项目级的gradle配置,在android块中添加下列配置:
signingConfigs {
    release {
        storeFile file("$path/$sign.jks")
        storePassword 'pwd'
        keyAlias 'keyAlias'
        keyPassword 'pwd'
    }

    debug {
        storeFile file("$path/$sign.jks")
        storePassword 'pwd'
        keyAlias 'keyAlias'
        keyPassword 'pwd'
    }
}
  1. 在Android Studio依次执行Build -> Clean ProjectBuild -> Rebuild Project

  2. 直接在Android Studio中运行项目即可

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment