Search code examples
androidadb

Looking to enable and disable (toggle) ADB or USB debugging using command line or in app


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.


Solution

  • The code that works is easy:

    Settings.Secure.putInt(getContentResolver(),Settings.Secure.ADB_ENABLED, 0); // 0 to disable, 1 to enable
    

    Edit/Update: Thanks to @MohanT for the following update:

    Settings.Global.putInt(getContentResolver(),Settings.Global.ADB_ENABLED, 0); // 0 to disable, 1 to enable
    

    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:

    > su
    # mount -o remount,rw -t yaffs2 /dev/block/mtdblock3 /system
    # cat /data/app/filename.apk > /system/app/filename.apk
    # mount -o remount,ro -t yaffs2 /dev/block/mtdblock3 /system
    # reboot