I'm trying to enable ADB (USB debugging) only when my application is running and disabling it when my application is not. I have full access to the phone and it is rooted, su
available, etc., but I cannot find a way to do the toggling.
What I've tried so far:
Process proc = Runtime.getRuntime().exec(new String [] { "su", "-c", "setprop", "persist.service.adb.enable", "0"});
proc.waitFor();
Process proc2 = Runtime.getRuntime().exec(new String [] { "su", "-c", "stop", "adbd"});
proc2.waitFor();
This however causes the phone to enter a reboot loop instantaneously.
You can achieve by following next steps:
Check whether ADB is currently enabled. To do that you can use a relevant global constant:
Settings.Global.ADB_ENABLED
for API 17 and above.Settings.Secure.ADB_ENABLED
prior to API 17.Use implicit
Intent
withSettings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS
action to open developers options, where user can enable or disable ADB.Code example:
Java
Kotlin
The code that works is easy:
Edit/Update: Thanks to @MohanT for the following update:
However, the app needs to be a system app to be able to use this. To get out of having to sign it, build a custom rom, etc.. I did the following to get it to be a system app.
First, I installed it regularly using eclipse, then adb shell:
Chris's answer is correct except the ADB_ENABLED field in Secure class has been depreciated and the string has been moved to Global class. So you can use below command -
From my experiences using setprop doesn't always work reliable, and might even conflict with the Settings > Applications > Development > USB Debugging option. Besides that it might be irritating for instance if USB debugging is enabled but adb doesn't work etc. Therefore using Settings.Secure.ADB_ENABLED is the prefered way... plus you always have the notification in the status panel.
If you don't want to go through the hassle to install your app on system partition when only trying to access Settings.Secure.ADB_ENABLED then you can instead rely on another app that is doing this work already:
This app is called ADB Toggle. You can find it in Google Play:
https://play.google.com/store/apps/details?id=com.ramdroid.adbtoggle
The library to access USB debug settings via ADB Toggle is available here:
https://github.com/ramdroid/AdbToggleAccessLib