在Linux上通过ADB与Java程序在Android设备上安装apk

问题描述:

我想从Java的内置文件管理器传递一个路径到Java与Linux上的Java程序安装在Android设备上安装apk。当代码执行时,使用文件管理器选择的apk永远不会被安装。在Linux上通过ADB与Java程序在Android设备上安装apk

下面是代码:

JFileChooser chooser = new JFileChooser(); 
      FileNameExtensionFilter filter = new FileNameExtensionFilter(
        "APK Files", "apk"); 
      chooser.setFileFilter(filter); 
      int returnVal = chooser.showOpenDialog(getParent()); 
      if(returnVal == JFileChooser.APPROVE_OPTION) { 
       System.out.println("You choose to open this file: " + chooser.getSelectedFile().getName()); 
       File file = new File(""); 
       System.out.println(file.getAbsolutePath().toString()); 

       try { 
        Process p1 = Runtime.getRuntime().exec("adb kill-server"); //for killing old adb instance 
        Process p2 = Runtime.getRuntime().exec("adb start-server"); 
        Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\""); 
        p3.waitFor(); 
        Process p4 = Runtime.getRuntime().exec("adb kill-server"); 
       } catch (Exception e1) { 

        System.err.println(e1); 
       } 

下面的代码应该安装APK:

Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\""); 
+1

你不应该使用'文件文件= chooser.getSelectedFile()' – ritesht93

+0

你有一个空文件...'文件文件=新文件(“”);'为什么你不使用文件选择器中的那个? –

+0

它还没有工作@ ritesht93 –

我想通了我自己,这里是代码:

JFileChooser chooser = new JFileChooser(); 
      FileNameExtensionFilter filter = new FileNameExtensionFilter("APK Files", "apk"); 
      chooser.setFileFilter(filter); 
      int returnVal = chooser.showOpenDialog(getParent()); 
      if (returnVal == JFileChooser.APPROVE_OPTION) { 
       File file = chooser.getSelectedFile(); 
       String filename = chooser.getSelectedFile().getName(); 
       try { 
        String[] commands = new String[3]; 
        commands[0] = "adb"; 
        commands[1] = "install"; 
        commands[2] = file.getAbsolutePath(); 
        Process p1 = Runtime.getRuntime().exec(commands, null); 
        p1.waitFor(); 
             } catch (Exception e1) { 
        System.err.println(e1); 
       } 
      } 

更改的行

File file = new File(""); 

File file = chooser.getSelectedFile(); 

也不要忘记检查

if(file.exists()) { 

验证文件。

希望它能工作。

+0

我试过了,但它不工作,还有什么建议吗? –

+0

确保您的设备具有开发人员选项.. – ELITE