13

I want to run these commands from java code:

adb shell settings put secure location_providers_allowed gps, wifi,network 

a broadcast -a android.location.GPS_ENABLED_CHANGE --ez enabled true

Please help me how to run from Android code.

2
  • so you want to run shell commands?
    – Behnam
    Commented Jul 30, 2015 at 19:03
  • yes I want to run shell commands to enable gps Commented Jul 30, 2015 at 19:13

2 Answers 2

9

You can use this method to run commands

private void runShellCommand(String command) throws Exception {
    Process process = Runtime.getRuntime().exec(command);
    process.waitFor();
}
5
  • 12
    any idea of this error "java.io.IOException: Cannot run program "adb": error=13, Permission denied" ?
    – Hai Hw
    Commented May 18, 2018 at 6:40
  • 2
    @HaiHw Have you ever solved that io exception? I'm getting the same thing. Commented Oct 6, 2018 at 17:45
  • @EugenioLopez I think it requires rooted device to run.
    – Hai Hw
    Commented Oct 8, 2018 at 6:18
  • No rooted device won't solve the problem @Eugenio Lopez Commented Sep 12, 2019 at 10:36
  • @HaiHw -> just write the command it self : for example :use "settings put secure location_providers_allowed" instead of "adb shell settings put secure location_providers_allowed..." Commented Dec 31, 2022 at 11:03
4

OK you will be needing Runtime class. There is a good tutorial on executing shell commands here. For a quick answer, try this:

String commandToRun = "adb shell settings put secure location_providers_allowed gps, wifi,network a broadcast -a android.location.GPS_ENABLED_CHANGE --ez enabled true";
Runtime.getRuntime().exec(commandToRun);

Not the answer you're looking for? Browse other questions tagged or ask your own question.