Android:无法以编程方式在我的 android 应用程序中运行 shell 脚本

Android: unable to run shell script in my android app programmatically

提问人:kgsharathkumar 提问时间:11/11/2023 最后编辑:James Zkgsharathkumar 更新时间:11/12/2023 访问量:47

问:

我的脚本位于设备的下载文件夹中,其路径为 /storage/emulated/0/Download/

我的shell脚本包含: testSharath.sh

#!/bin/sh
#!/system/bib/sh

echo "Hello from testSharath.sh"
ps -e

我试图在我的android代码中执行上面的shell脚本:

private void testShellScript() {
        File testPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String fileName = "testSharath.sh";
        File scriptFilePath = new File(testPath, fileName);
        try {
            Process process = Runtime.getRuntime().exec("/opt/homebrew/bin/adb shell chmod +x " +scriptFilePath);
            // Get the output stream of the process
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;

            // Read and print each line of the output
            while ((line = reader.readLine()) != null) {
                System.out.println("Sharath@@@@@@"+line);
            }
            // Close the reader
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

例外:

java.io.IOException:无法运行程序“/opt/homebrew/bin/adb”:error=2,没有这样的文件或目录

我的道路是正确的

java android adb android-shell

评论

1赞 Thomas Kläger 11/11/2023
您确定您的Android设备上安装了自制软件吗?这存在于您的Android设备上吗?/opt/homebrew/bin/adb
0赞 kgsharathkumar 11/13/2023
不,它安装在我的 macbook 上,adb 路径给出了相同的路径,所以我使用了相同的路径 /opt/homebrew/bin/adb,我不知道如何在我们的 android 设备中安装!!任何建议都欢迎在这里。@ThomasKläger

答:

0赞 Davit Hovhannisyan 11/12/2023 #1

试试这个方法

private void testShellScript() {
        try {

            String scriptFilePath = "/storage/emulated/0/Download/testSharath.sh";
    
            
            Process chmodProcess = Runtime.getRuntime().exec("chmod +x " + scriptFilePath);
            chmodProcess.waitFor();
    
            
            Process process = Runtime.getRuntime().exec(scriptFilePath);
    
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    
            String line;
    
            
            while ((line = reader.readLine()) != null) {
                System.out.println("Sharath@@@@@@" + line);
            }
    
            
            reader.close();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

评论

0赞 kgsharathkumar 11/13/2023
当我使用您的代码时,我遇到以下异常: java.io.IOException:无法运行程序“/storage/emulated/0/Download/testSharath.sh”:错误=13,权限被拒绝 2023-11-13 12:18:29.227 9001-9055 System.err com.lotus.sync.traveler W java.io.IOException:无法运行程序“/storage/emulated/0/Download/testSharath.sh”:错误=13,权限被拒绝 2023-11-13 12:18:29.228 9001-9055 System.err com.lotus.sync.traveler W 原因:java.io.IOException:错误=13,权限被拒绝