Installing apk on android device via ADB with Java program on Linux - java

I am trying to pass a path from Java's inbuilt file manager to ADB with java program on Linux to install apk on android device. When the code is executed the apk selected using file manager never gets installed.
Here is the code:
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);
}
The following code should install the apk:
Process p3 = Runtime.getRuntime().exec("adb install \"" + file.getAbsolutePath() + "\"");

I figured it out myself, and here is the code:
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);
}
}

Change the line
File file = new File("");
to
File file = chooser.getSelectedFile();
Also, don't forget to check
if(file.exists()) {
to validate the file.

I've spent a week working towards the same task for window system I have found out a simple solution to do this task, Here are some of the following steps that I have applied in my project
The First step is to download the ADB tool (Known as platform-tools) from this URL, and extract the downloaded file into your workspace directory.
Open the directory you downloaded the platform tools into
Create the Batch file if you don't aware how to create batch file follow the following steps
i. Open your text editor notepad or notepad++
ii. Save it as xyz.bat then it will be treated by the window system as a batch file
Open your batch file in your text editor and paste the following command
adb install "b2c.apk" && adb shell am start -n com.xyz.app/com.xyz.b2c.Activity.SplashScreen**
(Here there are two ADB command which separated by the ampersand sign.
The first command is for installing the APK in your Android devices
and the second one is to open the application )
i. b2c.apk is my android APK Which I want to install on my phone
ii. com.xyz.app is an android application package name and com.xyz.b2c.Activity.SplashScreen is an activity package name that I want to open
Save the file and close it, and then copy that file and paste it in the directory with the platform tools. And don't forget to place your APK file in this directory too
cd into the platform directory, and run this Java program:
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.util.Scanner;
public class TestClass {
static int progress = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String ls_str;
Process p = Runtime.getRuntime().exec("cmd /c xyz.bat", null, new File("E:\\Arun_Java_Workspace\\TestApplication\\platform-tools"));
DataInputStream ls_in = new DataInputStream(
p.getInputStream());
while ((ls_str = ls_in.readLine()) != null) {
System.out.println(ls_str);
}
} catch (Exception e) {
System.out.println("Exception e: " + e);
}
}
}

Related

When Grabbing a File through JFileChooser why does this fail?

I'm trying to understand Java Swing GUIs. So I created a simple GUI to select a File.
When I attempt to use the FFMPEG wrapper to get file information I get the following error.
java.io.IOException: Cannot run program "C:\File.mp4": CreateProcess error=193, %1 is not a valid Win32 application.
I feel like I'm missing something minor here.
Thanks.
JFileChooser fc = new JFileChooser();
int nReturnVal = fc.showOpenDialog(jPanel1);
File fVideo = null;
try {
if (nReturnVal == JFileChooser.APPROVE_OPTION) {
fVideo = fc.getSelectedFile();
//Now you have your file to do whatever you want to do
jPath.setText(fVideo.getAbsolutePath());
FFprobe ffprobe = new FFprobe(fVideo.getAbsoluteFile().toString());
FFmpegProbeResult probeResult = ffprobe.probe(fVideo.getAbsolutePath());
FFmpegFormat format = probeResult.getFormat();
System.out.format("%nFile: '%s' ; Format: '%s' ; Duration: %.3fs",
format.filename,
format.format_long_name,
format.duration);
jEndTime.setText("" + format.duration);
} else {
//User did not choose a valid file
}
}
catch (Exception ex) {
System.out.println(ex.toString());
}

How to start a program with command line arguments on Windows' cmd and force it to run foreground?

I'm executing a offline smoke test (SELENIUM) and to make it enable the macros in a excel spreadsheet that is generated by the system, I had to use a workaround where in the java code, I open the excel spreadsheet, save and close it, so that I can run the test and write values onto this spreadsheet. To open the excel spreadsheet (I setup excel to trust all macros), I wrote the following java code where I use command line commands to execute it:
#Then("Enable Worksheet Macros")
public void enableWorksheetMacros() throws InterruptedException, IOException, AWTException {
final String diretory = "c:\\automation\\";
final File file = new File(diretory);
final File[] files = file.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().toLowerCase(Locale.ENGLISH).endsWith(".xls");
}
});
if (files.length > 1) {
System.out.println("too many files");
} else if (files.length == 1) {
final String filename = files[0].getAbsolutePath();
final ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start", filename);
final Process p = pb.start();
p.waitFor();
Thread.sleep(5000);
final Robot r = new Robot();
r.keyPress(KeyEvent.VK_ALT);
r.keyPress(KeyEvent.VK_F4);
Thread.sleep(200);
r.keyRelease(KeyEvent.VK_F4);
r.keyRelease(KeyEvent.VK_ALT);
Thread.sleep(200);
r.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(200);
r.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(200);
r.keyPress(KeyEvent.VK_ENTER);
Thread.sleep(200);
r.keyRelease(KeyEvent.VK_ENTER);
Thread.sleep(200);
}
}
As you can see, right after opening the excel file, I just press ALT+F4 and press ENTER twice (it closes the file and save it). It was working fine, until I run this code in another environment, where when it opens the excel file, it is running background.
Is there a way I can make sure the program will run foreground?
EDIT:
I found this question on SU where the guy has the same problem I do, but no answer until now: https://superuser.com/questions/700879/windows-task-scheduler-starting-excel-in-background-how-to-force-to-start-in-fo

JFileChooser / FileWriter doesn't let me save in root of C: disk

I'm playing around and I made a notepad-like app using swing. Everything is working properly so far, except it's not letting me save the text file directly on C:/. On any other disk, and INCLUDING the root of the D: drive, or in folders of the C:/ disk it works like a charm. Why is this happening?
This is my code:
file_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFileChooser Chooser = new JFileChooser();
File DefaultDirectory = new File("C:/");
File Path;
int Checker;
FileFilter text_filter = new FileNameExtensionFilter(
"Text File (*txt)", "txt");
FileFilter another_filter = new FileNameExtensionFilter(
"Debug Filter (*boyan)", "boyan");
//
Chooser.setCurrentDirectory(DefaultDirectory);
Chooser.setDialogTitle("Save a file");
Chooser.addChoosableFileFilter(text_filter);
Chooser.addChoosableFileFilter(another_filter);
Chooser.setFileFilter(text_filter);
Checker = Chooser.showSaveDialog(null);
//
if (Checker == JFileChooser.APPROVE_OPTION) {
Path = Chooser.getSelectedFile();
System.out.println(Path.getAbsolutePath());
;// Just for
// debugging.
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(Path
.getAbsolutePath()));
String[] myString = textArea.getText().split("\\n");
for (int i = 0; i < textArea.getLineCount(); i++) {
writer.append(myString[i]);
writer.newLine(); // SO IT CAN PRESERVE NEW LINES
// (APPEND AND SPLIT ARE ALSO
// THERE
// BECAUSE OF THAT)
writer.flush();
}
JOptionPane.showMessageDialog(null, "File saved.", "",
JOptionPane.WARNING_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,
"File did not save successfuly.", "",
JOptionPane.WARNING_MESSAGE);
}
}
}
}
});
Thanks a lot in advance!
Usually, one does not have write permissions in C:\.
Start the app as a privileged user
One should not do that, as it is not intended by OS design. Changing permissions on C:\, or the system drive respectively, is a no-go.
Save into a sub-directory of System.getProperty("user.home"); (way to go)
The user home could also be a network folder with nighly backup in a domain network, for example. Especially for remote sessions (RDP, Citrix), this is often the case.
If you absolutely need to install a static file outside of the users folders, do it once, with an installer, configured to raise privileges (UAC).

Open folder containing file and highlight it

I'm needing to open a folder containing the specified file, and highlight this said file. I have been looking for this for long but I have been unlucky. Could someone explain how this could be done using java?
Would be much appreciated. I am able to open files, folders, but not open the containing folder and highlighting a file. Cross platform code would be a plus, or just point me to the direction! Thanks!
#UPDATE:
Basically I'm doing an image sorter. I have a ArrayList containing filenames, e.g. myarraylist.get(0) would return funny_cat.jpg
This can be a handy functionality to have in a program that works with files/folders. It's easy enough to actually open the containing folder using:
I want the user to be able to open the currently selected item in a JList and open the containing folder with the target file selected.
I would post the code but it is too long and most unnecesary for this question, I will however post below how I open an explorer window, for the settings section of program, in order to choose a new directory to use:
public void browseFolder(){
System.out.println("browsing!");
final JFileChooser fc = new JFileChooser();
File dir = new File(core.Loader.path);
fc.setCurrentDirectory(dir);
// Windows and Mac OSX compatibility code
if (System.getProperty("os.name").startsWith("Mac OS X")) {
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
} else {
fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
}
fc.setApproveButtonText("Choose directory");
int returnVal = fc.showOpenDialog(fc);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File f = fc.getSelectedFile();
// if the user accidently click a file, then select the parent directory.
if (!f.isDirectory()) {
f = f.getParentFile();
}
// debug
System.out.println("Selected directory for import " + f);
}
}
#UPDATE
I have found the solution, will post as answer below.
So, I just called this method from the action performed and it does the trick.
Basically, the solution was to make this terminal command:
open -R absolute/path/to/file.jpg
This is for Mac OS X only, below is my method I use:
public void openFileInFolder(String filename){
try {
Process ls_proc;
String mvnClean = "open -R " + core.Loader.path + "/" + file_chosen;
String OS = System.getProperty("os.name");
System.out.println("OS is: " + OS);
if (OS.contains("Windows")) {
//code ...
} else {
ls_proc = Runtime.getRuntime().exec(mvnClean);
}
} catch (Exception e){
System.err.println("exception");
}
}

How to Declare Folder Path?

I have a desktop application using Swing library. Application is running a batch file. So I created a lib folder in main project directory and put batch file in it. To run this, I am showing lib\a.exe to run this. It is working on my laptop. I exported .jar and put lib folder next to it. It is working on my laptop, but not working on some other laptops. How to fix this?
Error message is: Windows cannot found lib\a.exe.
String command = "cmd /c start lib\\a.exe";
try {
Runtime.getRuntime().exec(command);
increaseProgressBarValue();
} catch (IOException e) {
e.printStackTrace();
}
You need two things:
find the directory of the jar file of your application
call a.exe with the correct working directory
You can get the location of the jar with the getJar method below:
private static File getJar(Class clazz) throws MalformedURLException {
String name = clazz.getName().replace('.','/') + ".class";
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL url = cl.getResource(name);
System.out.println(url);
if (!"jar".equals(url.getProtocol())) {
throw new MalformedURLException("Expected a jar: URL " + url);
}
String file = url.getPath();
int pos = file.lastIndexOf('!');
if (pos < 0) {
throw new MalformedURLException("Expected ! " + file);
}
url = new URL(file.substring(0, pos));
if (!"file".equals(url.getProtocol())) {
throw new MalformedURLException("Expected a file: URL " + url);
}
String path = url.getPath();
if (path.matches("/[A-Za-z]:/")) { // Windoze drive letter
path = path.substring(1);
}
return new File(path);
}
To call lib\a.exe, you can do something like this:
File jar = getJar(MyClass.class); // MyClass can be any class in you jar file
File dir = jar.getParentFile();
ProcessBuilder builder = new ProcessBuilder();
builder.command("lib\\a.exe");
builder.directory(dir);
...
Process p = builder.start();
...
Maybe you have to try if this folder lib exists and if it doesn't than create it with
file.mkdir();
This is a just a checking. But your filepath must be like this ../lib/a.exe.

Categories