SSH Connection with Android Studio - Android Apps and Games

Hello Together,
I have a Problem by Programming a ssh connection between pc and android phone.
I already wrote the code and i ran it in eclipse and there it works.
Now i copy and pasted it into android studio and it is running with an error.
I am using Maverick SSH2 example code
The Problem : i use the command executeCommand("echo > help.txt") and in eclipse the programm sends the command and finishs.
In contrast to Android Studio, when i use executeCommand there it sends ("echo > help.txt"), too but still stays in executeCommand. All Commands after this wont be called. It stucks in the command.
Does anyone has an idea ?
I dont know what to do, i thought when it is running in eclipse it has to run in android studio as well.
Thanks for Help!
Fiixx
the Code:
import com.sshtools.net.SocketTransport;
import com.sshtools.ssh.ChannelOpenException;
import com.sshtools.ssh.PasswordAuthentication;
import com.sshtools.ssh.SshAuthentication;
import com.sshtools.ssh.SshClient;
import com.sshtools.ssh.SshConnector;
import com.sshtools.ssh.SshException;
import com.sshtools.ssh.SshSession;
import com.sshtools.util.IOStreamConnector;
import java.io.IOException;
/**
* Created by Zouca on 31.10.2016.
*/
class SSH implements Runnable {
@override
public void run() {
//Code wich should be run
try {
SshConnector con = SshConnector.createInstance();
SshClient ssh;
ssh = con.connect(new SocketTransport("192......", 22),
"username");
PasswordAuthentication pwd = new PasswordAuthentication();
pwd.setPassword("password");
if(ssh.authenticate(pwd)== SshAuthentication.COMPLETE)
{System.out.println("Authentication succeeded");}
SshSession session = ssh.openSessionChannel();
session.executeCommand("echo > hello.txt");
}
catch (SshException | IOException | ChannelOpenException e) {
e.printStackTrace();
System.out.println("Authentication failed");
}
System.out.println("!!! I came to the End ! Never seen this at console !!");
}
}

Related

Writing an android root application

Hi
I've written a number of 'standard' Android applications (using Eclipse) and I've rooted my G1, but I don't know where to start with writing an application that uses root access.
Is it simply a case of sending shell commands to the localhost shell from within my app, or can I (somehow) request root access from Java and call lots of fun 'hidden' APIs directly?
Are there any source code examples of a simple root application? I Google'd extensively but couldn't find one
Thanks
You can execute shell commands using something like this:
Code:
final Runtime runtime = Runtime.getRuntime();
try {
runtime.exec("su"); //or whatever command.
}
catch (IOException e) {
e.printStackTrace();
}
Once you execute su, you should be able to run other commands. I've not tried it myself, but you get the general idea. If you have superuser whitelist installed, it should prompt you to allow the app to access root.
Got it - thanks!
Now I just have to think of something fun to do with it!
hi...
now when I say that one. I am not able to get the root access. what is the reason...
rajendran.bits said:
now when I say that one. I am not able to get the root access. what is the reason...
Click to expand...
Click to collapse
Is the phone you are testing on rooted? You need a properly rooted image (Nandroid) to use this in the emulator as well.
Plummet said:
Hi
I've written a number of 'standard' Android applications (using Eclipse) and I've rooted my G1, but I don't know where to start with writing an application that uses root access.
Is it simply a case of sending shell commands to the localhost shell from within my app, or can I (somehow) request root access from Java and call lots of fun 'hidden' APIs directly?
Are there any source code examples of a simple root application? I Google'd extensively but couldn't find one
Thanks
Click to expand...
Click to collapse
Having root will let your app call shell commands to do things root could do. As far as hidden APIs, it's not going to give you any special capabilities there. If there are any hidden APIs, probably only Google knows about them
There is already a root app
www.androidactivity.com/root/root.apk
Breakthecycle2 said:
There is already a root app
www.androidactivity.com/root/root.apk
Click to expand...
Click to collapse
I pretty sure the OP is just saying that they want to write applications that can use root access, not an application for root access.
mlevin said:
If there are any hidden APIs, probably only Google knows about them
Click to expand...
Click to collapse
That's absurd. Android is open source. There can be no truly hidden APIs. There can be things left out of the SDK, in which case you can assume the feature to be "in flux" and not reliable across versions, but nothing can be hidden from the source code.
lbcoder said:
That's absurd. Android is open source. There can be no truly hidden APIs. There can be things left out of the SDK, in which case you can assume the feature to be "in flux" and not reliable across versions, but nothing can be hidden from the source code.
Click to expand...
Click to collapse
I have to agree with this.
Breakthecycle2 said:
I have to agree with this.
Click to expand...
Click to collapse
Well, in Hero and other closed-source versions of Android like the oPhone firmware, there COULD be some closed API's...
Still no solution to gain root from java code ?
I tried "su", but it doesn't works (I have a rooted phone).
I'd like to read gmail messages database for a new widget ... impossible without root.
I can get access to database if I change rights for the db file.
You should contact with one of the authors of a root app.
Search for "root" in the market.
You could do something like that:
Code:
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command+"\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.d("*** DEBUG ***", "Unexpected error - Here is what I know: "+e.getMessage());
return false;
}
finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
Or in your case (change the owner of a file) ... less code:
Code:
public static boolean runChmod777(String myfile) {
Process process = null;
try {
process = Runtime.getRuntime().exec("su -c chmod 0777 myfile");
process.waitFor();
} catch (Exception e) {
Log.d("*** DEBUG ***", "Unexpected error - Here is what I know: "+e.getMessage());
return false;
}
finally {
try {
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
EDIT: Ah ... This shows a "chmod" ...
harry_m said:
You could do something like that:
Code:
public static boolean runRootCommand(String command) {
Process process = null;
DataOutputStream os = null;
try {
process = Runtime.getRuntime().exec("su");
os = new DataOutputStream(process.getOutputStream());
os.writeBytes(command+"\n");
os.writeBytes("exit\n");
os.flush();
process.waitFor();
} catch (Exception e) {
Log.d("*** DEBUG ***", "Unexpected error - Here is what I know: "+e.getMessage());
return false;
}
finally {
try {
if (os != null) {
os.close();
}
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
Or in your case (change the owner of a file) ... less code:
Code:
public static boolean runChmod777(String myfile) {
Process process = null;
try {
process = Runtime.getRuntime().exec("su -c chmod 0777 myfile");
process.waitFor();
} catch (Exception e) {
Log.d("*** DEBUG ***", "Unexpected error - Here is what I know: "+e.getMessage());
return false;
}
finally {
try {
process.destroy();
} catch (Exception e) {
// nothing
}
}
return true;
}
EDIT: Ah ... This shows a "chmod" ...
Click to expand...
Click to collapse
Thank you very much for this code.
I don't think I'll be able to use the "chmod" method. Gmail change permissions each time he check for mails :/
But I may at least copy the database somewhere and work on a copy.
Another idea to open this protecteed database ?
koxx said:
Thank you very much for this code.
I don't think I'll be able to use the "chmod" method. Gmail change permissions each time he check for mails :/
But I may at least copy the database somewhere and work on a copy.
Another idea to open this protecteed database ?
Click to expand...
Click to collapse
Mmmmh ... just a thought. How about reading the calendar-entries by using the Google Calendar API?
Not sure if that works ... but this way you don't need root.
http://code.google.com/intl/en-EN/apis/calendar/
http://davanum.wordpress.com/2007/12/05/android-use-atomgdata-api-to-access-the-google-calendar/
harry_m said:
Mmmmh ... just a thought. How about reading the calendar-entries by using the Google Calendar API?
Not sure if that works ... but this way you don't need root.
http://code.google.com/intl/en-EN/apis/calendar/
http://davanum.wordpress.com/2007/12/05/android-use-atomgdata-api-to-access-the-google-calendar/
Click to expand...
Click to collapse
I'am talking about GMAIL databases reading ... hehehe
Close sources, no API, more complicated
For calendar, everything is fine, my widget works fine without rooting.
this is interesting have no idea what im talking about but can u set up a gmail pop/imap whatever account to the widget
Plummet said:
Got it - thanks!
Now I just have to think of something fun to do with it!
Click to expand...
Click to collapse
How about writing a root app that picks up sms/mms/voicemail intents and activates the LEDs for Hero roms? That would be a huge one here for people using Hero. You could basically write it to act as a service as it'd be pointless to have a gui for it.
I want to read the wifi keys to save them without using titanium backup:
File sdcard = Environment.getDataDirectory();
//Get the text file
File file = new File(sdcard,"wifi/bcm_supp.conf");
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
text.append('\n');
}
}
But the Log says that: FILE NOT FOUND :java.io.FileNotFoundException: /data/wifi/bcm_supp.conf (Permission denied)
The i tried to put:
try {
runtime.exec("su"); //or whatever command.
}
catch (IOException e) {
e.printStackTrace();
}
first and i granted superuser right to my app with this part, but the same error appears... how can i read files from root directory??

Simple Android cross environment for native ARM development

Hi geeks,
of course native ARM code compiling could be done with the full blown SDK+NDK, but honestly i found it way too much in some cases.
So i started investigating about a more simple cross environment.
There are many solutions out there, but IMHO the easiest way is to use the agcc wrapper written by Andrew Ross.
To make it comfortable, one of the prebuilt toolchains from the android source repository is used (gcc-4.4.0).
The environemnt will create dynamically linked executables, so we will link against the bionic libs here.
If you don't know what i'm talking about, follow the links at the bottom or step over to use your phone as a phone.
In fact this solution is not re-inventing the wheel, but more a walk on a practical trail for native development.
Everything could be easily put together and equipped with the essential source packages, you get a very handy solution to compile simple c-code for your Android platform.
Only minor tweaks had been done to the agcc wrapper, and you might do as well to fit it to your needs.
Grab the complete package here:
http://dl.dropbox.com/u/8815400/android-agcc-4.4.0.tar.gz
Everything was choosen to work nicely for the Milestone platform.
To make it the most compatible i decided to use the includes and libs from the eclair branches.
It might also work for other devices, but some tweaks could be required then.
To start development for your platform you'll need a more or less up-to-date linux OS on your host.
Minimum should be:
Debian 5.0
Ubuntu 10
...
Simply extract the archive to a directory of your choice, user rights should be O.K. (the default directory of the package would be /opt).
To make everything work properly, it is required to modify the $DROID variable insdide agcc wrapper to point at your working directory (e.g. /opt/android).
It is also required to add the path to the android toolchain to the PATH variable of your system. There are different attempts to do so.
E.g. on Debian 5.0 add the following line at the end of your .bashrc:
Code:
export PATH=$PATH:/opt/android/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/bin
To check, if the toolchain is working, create a simple hello.c like this:
Code:
#include <stdio.h>
main()
{
printf ("Hello World!\n");
}
Compile the code on your host:
./agcc hello.c -o hello
The result is a 32-bit ELF executable for ARM. Transfer the binary to your platform and make it executable.
You might use adb to do so (usb debugging needs to be activated on your device).
Attach the Milestone to your host and type:
./adb start-server
./adb push hello /data/local
./adb shell
Now in the shell on your device type:
$ cd /data/local
$ chmod +x hello
$ ./hello
There you go!
It is also possible to compile even more complex tools using MAKEFILE.
Some details might be discussed here, if there's some interest.
Useful links:
The essential packages had been taken from source packages over here:
http://android.git.kernel.org/
Also some libs had been grabbed from this project:
http://gitorious.org/rowboat
Original agcc wrapper could be found here:
http://plausible.org/andy/agcc
Further information:
http://labs.embinux.org/index.php/Toolchain_For_Android
http://android-dls.com/wiki/index.php?title=Compiling_for_Android
http://elinux.org/Android_Tools
Happy hacking!
scholbert
Examples ...
You'll find some simple c-code examples for console here.
Most of them would require root access.
A good location to store them locally on your device is /data/local.
omapinfo v.1.0.0 (reads out some very special registers )
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
int main() {
printf("omapinfo v.1.0.0\n");
int fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd < 0) {
printf("Could not open memory\n");
return 1;
}
// map L4 core registers @ 0x4800 0000 to memory
volatile unsigned long *L4_core_base;
L4_core_base = (unsigned long*) mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x48000000);
if (L4_core_base == MAP_FAILED) {
printf("Mapping L4 core base failed\n");
close(fd);
return 1;
}
// read some register values
printf("STATE : %8x \n",L4_core_base[0x22f0/4]); // check HS bit, boot mode
printf("PKEY0 : %8x \n",L4_core_base[0x2300/4]); // read out RPUB_KEY_H_0
printf("PKEY1 : %8x \n",L4_core_base[0x2304/4]); // read out RPUB_KEY_H_1
printf("PKEY2 : %8x \n",L4_core_base[0x2308/4]); // read out RPUB_KEY_H_2
printf("PKEY3 : %8x \n",L4_core_base[0x230c/4]); // read out RPUB_KEY_H_3
printf("PKEY4 : %8x \n",L4_core_base[0x2310/4]); // read out RPUB_KEY_H_4
// map L4 wakeup registers @ 0x4830 00000 to memory
volatile unsigned long *L4_wakeup_base;
L4_wakeup_base = (unsigned long*) mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x48300000);
if (L4_wakeup_base == MAP_FAILED) {
printf("Mapping L4 wakeup base failed\n");
close(fd);
return 1;
}
//read CONTROL_ID
printf("CPU-ID: %8x \n",L4_wakeup_base[0xa204/4]);
close(fd);
}
Cheers,
scholbert
I'm sorry but I don't understand what the end result is.
My brain ain't big enough to figure out which problem this is solving.
Hi zeppelinrox!
zeppelinrox said:
I'm sorry but I don't understand what the end result is.
Click to expand...
Click to collapse
The end result is a very lightweight cross environment to write simple progs for your android device (c-code based).
The package could easily be installed and run on a netbook with linux OS.
Nothing more nothing less..
zeppelinrox said:
My brain ain't big enough to figure out which problem this is solving.
Click to expand...
Click to collapse
You don't need a big brain and there's also no specific problem to solve.
As i tried to point out, i needed this kind of tool to compile some very basic command line tools.
Pushing the whole Android SDK+NDK was way too much for this.
I did not find any package like this, so i thought i put it together myself and share it.
Of course this is mostly for fun, but could be used for hardware-oriented programming and similar stuff.
By using the memory mapped register access, some kernel settings could easily be overridden and this maybe useful for testing new drivers and stuff.
E.g. i'll try to compile i2c-tools next... let's see if it works .
Have fun!
scholbert
This is only practical for small native utility.
YongkiCA said:
This is only practical for small native utility.
Click to expand...
Click to collapse
That's what i said....
BTW here's another small native utility!
Look at the project page for info.
http://www.lm-sensors.org/wiki/I2CTools
Regards,
scholbert
Thanks for this thread scholbert! Thanks for taking the time I haven't tried this yet, but I may later, but right know acknowledging your efforts! Wonderful job
Phone:motorola charm
Kernel:2.6.29-omap1
# omapinfo
Code:
omapinfo v.1.0.0
STATE : 21b
PKEY0 : 62b63f1d
PKEY1 : 708c4d79
PKEY2 : cbb457fb
PKEY3 : f6272e49
PKEY4 : 4f2e156f
CPU-ID: 4b7ae02f

[Q] Run Linux commands in Application - Busybox?

I'm a new to Android development and am writing an application that should execute Linux commands on button press. However, for whatever reason, I can't make any of them work.
Code:
public void getSU(View view) {
try {
Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
This works to obtain SuperUser privileges for the app, but any other commands like "cp" or "mv" just plain don't work.
Final note: I do have Busybox installed and properly symlinked.
Does anyone have any ideas about what I'm doing wrong, or am I committing some sort of egregious Android error?

Open local html file in Android Browser?

I want to open local html file with default Android browser:
Code:
Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setComponent(new ComponentName(getBrowserPackage(), "com.android.browser.BrowserActivity"));
intent.setDataAndType(Uri.parse("file:///sdcard/mypage.html"), "text/html");
startActivity(intent);
Yes, I know that there my might be anohter browser. And when I input url `file:///sdcard/mypage.html` directly in browser, it is opened. `getBrowserPackage()` returns desired package name, because in logcat I see:
I/ActivityManager(304): START {act=android.intent.action.VIEW dat=file:///sdcard/mypage.html typ=text/html flg=0x54800000 cmp=com.google.android.browser/com.android.browser.BrowserActivity u=0} from pid 28817
Click to expand...
Click to collapse
But browser fails to open the page.
Permissions for file:
**-rw-rw-r--**
Also tried
Code:
File dir = Environment.getExternalStorageDirectory();
File f = new File(dir, "mypage.html");
but it's not working, despite that calling
Code:
f.exists()
returns true
Any suggestions?

[HOW TO] Make your own Android Toolkit for Windows in C# - Make it to your liking!

[HOW TO] Make your own Android Toolkit for Windows using C#​
In this tutorial it will show you how to use Windows C# to create your very own toolkit for use of simple ADB commands.
Such as:
- Rebooting your Device.
- Rebooting to Recovery/CWM or Bootloader.
- Installing APK's directly to your device.
- Installing general files to the SDCARD
- Pushing and Pulling files
Or if you look into it enough you can Implement such features as:
- Rooting your Device.
- Unlocking/Locking Bootloader.
- File Permissions.
( These won't Be covered in this Tutorial, as they require much more time, especially Rooting. )
Knowledge required​
- A set up Visual C# Studio ready to use on your PC. It can be downloaded here : http://www.microsoft.com/visualstudio/eng/downloads
- General knowledge about C# such as using buttons, text boxes and the actual studio.
Getting Started​
So once you have set up your Visual C# studio, create a windows Form application and mess around with the user interface a little if you like to make it to your taste. :highfive:
So here is a picture of my preview:
I have applied a few different ADB tasks buttons as you can see, Including APK install using a Textbox to store your chose directory of the selected file.( As well as a few colour and form name changes to make it more appealing )
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Writing the ADB commands to the chosen Buttons in your application.​
Now we want to click on the ADB reboot button until it changes to the code layout as such...
Now we have this layout we want to add the namespaces :
using System.IO;
using System.Diagnostics;
These will allow use for CMD and Process features.
Adding ADB commands to the Buttons​
How you have your ADB reboot button code ready to write to.
Use this function: and insert it in between the two Curly brackets
{
var process = Process.Start("CMD.exe", "/c adb reboot");
process.WaitForExit();
}
[/B]
Such as:
MessageBox.Show("Device is Now Rebooting..");
The line uses CMD.exe as the process which will run it as an application and use the /c (command) to execute "adb reboot".
Which will reboot the connected device as long as it's android..
So once you have gone through using the correct ADB commands your application code will look like this..
The ADB wont work yet when running a debug version, so don't try and execute any commands yet.. The adb.exe and a couple of other files need to be stored in the same folder as your toolkit as a resource for ADB to run off of.
Using Textboxes and OpenFileDialog to Install .APK files.​
So once you have clicked the two buttons and textbox.
Setting you up ready to code it will look like this:
ADDING CODE
Assuming you have added OpenFileDialog to your Form Design!
We can now add code to the 2 buttons and text box.
It will look like this after adding the following to segments of code.
Add this to Open APK button:
openFileDialog1.InitialDirectory = @"C:\";
openFileDialog1.Title = "Select your APK..";
openFileDialog1.FileName = "Choose File..";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.Filter = " .APK|*.apk";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}​
And add this to Install APK file button:
var process = Process.Start("CMD.exe", "/c adb install " + textBox1.Text);
process.WaitForExit();
MessageBox.Show(".APK is Installed", "", MessageBoxButtons.OK, MessageBoxIcon.Information);​
Now' that is almost it!
Once you have saved and Built a release version of the tool.
Put the .exe from release of the saved directory into a folder ALONG with ADB.exe, ADBWinAPI.DLL and ADBWINUSBAPI.DLL
These ADB files a part of the Android platform tools from the SDK manager. You should already have these if you want to do this process
- If not just google them or download the SDK manager and find them.
Now That's it!
I think I have covered most parts if you want to write your own processes for ADB to execute feel free to do so..
I thought it maybe nice for people who liking personalizing their devices to also personalize toolkits for themselves also!
Thanks and Enjoy if you have any Issues or problems feel free to ask!
Enjoy, QuantumCipher
You can keep upto date on anything I'm doing via Facebook http://www.facebook.com/Quantumcipher
or Youtube https://www.youtube.com/user/QuantumCipher
Thanks for the feedback everyone (Y) ....
Not sure if everyone has no idea what C# is or Just like using developer stuff..
Thanks....
Thanks Man.. i was looking for the same... Can you give me tutorials for rooting and other aspects... Im wating for you....
Also, you could show them how to integrate my AndroidLib .NET library into it to handle all of the adb stuff
Nice!! Reserved below Also!! I don't have experience with C# but I can learn by mistakes!
Very nice tutorial!
As long it is a nexus device the rooting and flash cwm thing is the same thing except you're using fastboot commands.
kind regards
How can I get output text from cmd.exe? For example, if I have another textbox, and I want to display text. Text can be
Waiting for device ......(in case device not found)
Adb server start......depend on cmd.exe output.
Sent from my Spirit S using xda premium
regaw_leinad said:
Also, you could show them how to integrate my AndroidLib .NET library into it to handle all of the adb stuff
Click to expand...
Click to collapse
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
DeepUnknown said:
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
Click to expand...
Click to collapse
yes, it works but there is cmd.exe window pop up....after I close this window, then I can get the output. it is not in real time...thanks
DeepUnknown said:
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
Click to expand...
Click to collapse
Thanks for sharing this code!
Is it possible for the output to show as it appears on cmd?
Thanks
Saw this last week, never programmed with C# but thought what the hell i have already done C++ at uni, some java for making an android app
so i downloaded VS2012 opened up google and went nuts, i now have a toolkit so far, downloads the sdk, extracts the sdk ( yea i know i could just pack the adb .dll's and .exe but while learning the language i might as well learn other stuff.) and i have backup/restore options for /sdcard/ and /dcim/ folders and a folder picker for backing up, contacts backup/restore ( looking to create something that will export it as a CSV or something)
so a big thanks for shedding some light on where to get started on this, now i cant stop and want to make a toolkit will loads of features lol :victory:
0lzi said:
Saw this last week, never programmed with C# but thought what the hell i have already done C++ at uni, some java for making an android app
so i downloaded VS2012 opened up google and went nuts, i now have a toolkit so far, downloads the sdk, extracts the sdk ( yea i know i could just pack the adb .dll's and .exe but while learning the language i might as well learn other stuff.) and i have backup/restore options for /sdcard/ and /dcim/ folders and a folder picker for backing up, contacts backup/restore ( looking to create something that will export it as a CSV or something)
so a big thanks for shedding some light on where to get started on this, now i cant stop and want to make a toolkit will loads of features lol :victory:
Click to expand...
Click to collapse
Thanks very much for the kind remarks everybody, it's extremely nice to know that this tutorial has helped you get into C# and this exact comment you made is what is going to get me back into this scene :good:
I will start looking into rooting devices and how I can incorporate them into ADB programs and maybe other things.
DeepUnknown said:
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
Click to expand...
Click to collapse
Hey all together,
1st THX for this great thread!
-
I have some problems to get the "fastboot" output in my c# programm...
i tired it with adb and some other cmd tools all give me an output but fastboot not
Here my cmd launcher:
//Launch silent CMD
private string run_silent_cmd(string args, bool w = true, bool o = true)
{
string request = "";
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/Q/C" + args;
process = Process.Start(startInfo);
if (o)
{
request = process.StandardOutput.ReadToEnd();
}
if (w)
{
process.WaitForExit();
}
return request;
}
can some1 gimme a kick in the right direction?
Regards,
Sebastian
k1ll3r8e said:
Hey all together,
1st THX for this great thread!
-
I have some problems to get the "fastboot" output in my c# programm...
i tired it with adb and some other cmd tools all give me an output but fastboot not
Here my cmd launcher:
//Launch silent CMD
private string run_silent_cmd(string args, bool w = true, bool o = true)
{
string request = "";
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/Q/C" + args;
process = Process.Start(startInfo);
if (o)
{
request = process.StandardOutput.ReadToEnd();
}
if (w)
{
process.WaitForExit();
}
return request;
}
can some1 gimme a kick in the right direction?
Regards,
Sebastian
Click to expand...
Click to collapse
Have you added the Fastboot.exe to your resources - for the program your making?
QuantumCipher said:
Have you added the Fastboot.exe to your resources - for the program your making?
Click to expand...
Click to collapse
Nope, its just in an subfolder so that the user can upgrade the version if a new 1 comes out
i call the function like run_silent_cmd(KIT + "adb\\fastboot.exe some commands")
@k1ll3r8e
k1ll3r8e said:
Hey all together,
1st THX for this great thread!
-
I have some problems to get the "fastboot" output in my c# programm...
i tired it with adb and some other cmd tools all give me an output but fastboot not
Here my cmd launcher:
//Launch silent CMD
private string run_silent_cmd(string args, bool w = true, bool o = true)
{
string request = "";
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/Q/C" + args;
process = Process.Start(startInfo);
if (o)
{
request = process.StandardOutput.ReadToEnd();
}
if (w)
{
process.WaitForExit();
}
return request;
}
can some1 gimme a kick in the right direction?
Regards,
Sebastian
Click to expand...
Click to collapse
Your variable "args" should include the path for Fastboot.exe or your code should be like this (I'm using an example path in this example, you must replace it with your own path):
startInfo.Arguments = "/Q/C " + @"C:\AdbTools\fastboo.exe " + args;
OR
startInfo.Arguments = String.Join(" ", "/Q/C", Path.Combine("C:","AdbTools","fastboot.exe"), args);
(The first parameter passed in String.Join refers to separator string)
-------------------------------------------------------
@menglim
menglim said:
yes, it works but there is cmd.exe window pop up....after I close this window, then I can get the output. it is not in real time...thanks
Click to expand...
Click to collapse
try this, enter it after you define ProcessStartInfo (let's say you named it just like in the code snippet I gave)
startInfo.CreateNoWindow = true;
now window should disappear.
if not, remove this line and keep the one I gave you in this comment: startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
-------------------------------------------------------
@squabbi
squabbi said:
Thanks for sharing this code!
Is it possible for the output to show as it appears on cmd?
Thanks
Click to expand...
Click to collapse
it's possible but a bit tricky, you can start by making the "Label" / "TextBlock" / "TextBox" or whatever UIElement you are using and set it's background to black and it's foreground to white, then choose "Console" font family, this should get you "Close enough" to the same output style
Note for anyone passing by this page:
When dealing with Directories in C#, ALWAYS use this code snippet, I will explain why at the end of this comment:
Path.Combine("Root Dir","SubDir1","SubDir2","File_You_Want_To_Use");
Where: Root Dir could be any logical partition you have on your HDD or the root dir of your application.
in my case in Droid Manager I have an internal variable (called: ExecutablePath) that saves the path of Droid Manager after installation, so in my case when I want to call an Init.d script example I use the following code snippet:
Path.Combine(ExecutablePath,"Initd_Scripts", "File_Name");
When wanting to add multiple strings together use this following code snippet:
String.Join(Separator String, params string Arguments);
Those ensure the best result, by that I mean be sure system will read them they way they are intended to be read, if you use "+" or "\\" or "@" there might be some misunderstanding by the system which happened to me when I started learning programming 7 years ago.
Good Luck
DeepUnknown said:
@k1ll3r8e
Your variable "args" should include the path for Fastboot.exe or your code should be like this (I'm using an example path in this example, you must replace it with your own path):
startInfo.Arguments = "/Q/C " + @"C:\AdbTools\fastboo.exe " + args;
OR
startInfo.Arguments = String.Join(" ", "/Q/C", Path.Combine("C:","AdbTools","fastboot.exe"), args);
Click to expand...
Click to collapse
Thx for the info
but... "Path.Combine" tells me only 2 strings can be combined so its useless for me coz i get the path via "Application.StartupPath" and i have 2 subfolder this means i have 3 strings to combine^^
thats why i set some vars in my form...
//KIT Vars
private static string KIT = Application.StartupPath + "\\";
private static string ADB = KIT + "adb\\adb.exe";
private static string FBT = KIT + "adb\\fastboot.exe";
also fastboot will not output anything
i googled a bit and found some threads... in this threads they say fastboot dun use the "flush" command (!?) this will mean the output is not grab able...
i think they are right^^ coz adb or cmd it self will output something via my function only fastboot returns nothing...
menglim said:
yes, it works but there is cmd.exe window pop up....after I close this window, then I can get the output. it is not in real time...thanks
Click to expand...
Click to collapse
squabbi said:
Thanks for sharing this code!
Is it possible for the output to show as it appears on cmd?
Thanks
Click to expand...
Click to collapse
k1ll3r8e said:
Thx for the info
but... "Path.Combine" tells me only 2 strings can be combined so its useless for me coz i get the path via "Application.StartupPath" and i have 2 subfolder this means i have 3 strings to combine^^
thats why i set some vars in my form...
//KIT Vars
private static string KIT = Application.StartupPath + "\\";
private static string ADB = KIT + "adb\\adb.exe";
private static string FBT = KIT + "adb\\fastboot.exe";
also fastboot will not output anything
i googled a bit and found some threads... in this threads they say fastboot dun use the "flush" command (!?) this will mean the output is not grab able...
i think they are right^^ coz adb or cmd it self will output something via my function only fastboot returns nothing...
Click to expand...
Click to collapse
Nope not true, Path.Combine takes more than two args. I've passed to it 4 args in Droid Manager, here is a screenshot about it:
Also be sure that you remove this:
using System.Windows.Shapes;
and replace it with:
using System.IO;
so that the correct "Path" class is being called. if it's not there then no need to do anything just be sure System.IO is added.
Also "Flush" command means the same as in the image below:
Fastboot does show output but on certain commands, for example when you type: Fastboot devices
you will get an output IF AND ONLY IF you have a connected device in Fastboot mode.
Or when you unlock a Sony Xperia bootloader you will get output.
DeepUnknown said:
Nope not true, Path.Combine takes more than two args. I've passed to it 4 args in Droid Manager, here is a screenshot about it:
Also be sure that you remove this:
using System.Windows.Shapes;
and replace it with:
using System.IO;
so that the correct "Path" class is being called. if it's not there then no need to do anything just be sure System.IO is added.
Also "Flush" command means the same as in the image below:
Fastboot does show output but on certain commands, for example when you type: Fastboot devices
you will get an output IF AND ONLY IF you have a connected device in Fastboot mode.
Or when you unlock a Sony Xperia bootloader you will get output.
Click to expand...
Click to collapse
Thx for the fast reply
My doc beginning is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
but see img below
the thing with the streamwriter i dun understand^^ - tried it yesterday a few times but with no luck
Finally i think im too dumb... coz "adb.exe version" give me an output and "adb start-server" brings my proggy to hangup^^
k1ll3r8e said:
Thx for the fast reply
My doc beginning is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
but see img below
the thing with the streamwriter i dun understand^^ - tried it yesterday a few times but with no luck
Finally i think im too dumb... coz "adb.exe version" give me an output and "adb start-server" brings my proggy to hangup^^
Click to expand...
Click to collapse
Hmmm... Windows Form, to be honest the last time I worked with Windows Form application was two years ago, since 2011 I program WPF projects, which Microsoft is focusing on + it is more flexible when it comes to App UI and data bindings, that's why I use it.
There are differences between Windows Form and WPF unfortunately :-/
By the way if you consider switching to WPF you need to also learn XAML language (not XML, it's XAML) so you can play with the UI the way you want.
Good luck

Categories

Resources