make android source using adb shell command "cat" - android

I want to use shell command, 'cat'.
I want to copy the "abc.jpg" file..But It didn't operate.
What is the problem? Thank you.
public void onClick(View v) {
Runtime runtime = Runtime.getRuntime();
Process process;
try {
String cmd = "cat /sdcard/0/Pikicast/abc.jpg>/sdcard/0/apk_backups/abc.jpg";
process = runtime.exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
Log.i("test",line);
}
} catch (Exception e) {
e.fillInStackTrace();
Log.e("Process Manager", "Unable to execute top command");
}
}

I have modified your code a little. Kindly try this.
String[] command = {"cat","/sdcard/0/Pikicast/abc.jpg>/sdcard/0/apk_backups/abc.jpg"};
StringBuilder cmdReturn = new StringBuilder();
try {
ProcessBuilder processBuilder = new ProcessBuilder(command);
Process process = processBuilder.start();
InputStream inputStream = process.getInputStream();
int c;
while ((c = inputStream.read()) != -1) {
cmdReturn.append((char) c);
}
prompt.setText(cmdReturn.toString());
Log.w("test",cmdReturn);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Process Manager", "Unable to execute top command");
}

Related

I want when Click button in android studio make connection with python

I tried clicking on a button to make connection with python
but it doesn't run except it only run in main
This is the code that run the connection
public class link {
public static void main(String a[]) {
try {
Process p = Runtime.getRuntime().exec(
"python C:/Users/ASUS/Desktop/sendingCode/jaad/app/test.py");
Scanner in = new Scanner(new InputStreamReader(
p.getInputStream()));
String line = "";
while ((line = in.nextLine()) != null) {
// display each output line form python script
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Once I put the previous code on button it wont work with me i dont know why
recordBtn=(Button)findViewById(R.id.recordBtn);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
Process p = Runtime.getRuntime().exec(
"python C:/Users/ASUS/Desktop/sendingCode/jaad/app/test.py");
Scanner in = new Scanner(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = in.nextLine()) != null) {
// display each output line form python script
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
});

start test apk in another apk

Android version: 4.1 .
I want to test my apk without pc, so i write android apk to do it.
Process proc = Runtime.getRuntime().exec(command);
try {
if (proc.waitFor() != 0) {
System.err.println("exit value = " + proc.exitValue());
// proc.waitFor();
}
BufferedReader in = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while ((line = in.readLine()) != null) {
stringBuffer.append(line+"\n");
}
// proc.waitFor();
System.out.println(stringBuffer.toString());
Log.i("info",stringBuffer.toString());
return stringBuffer.toString();
} catch (InterruptedException e) {
System.err.println(e);
}
and the command is
am instrument -w -e deleteCase no com.calculator.test/com.xx.test.runner.Runner1
but it's not worked.

Run bash script from android app

I want to change the value of variable in xml. The value is based on another file which read by editXml.sh. So I need to run the editXml.sh before app is compiled.
I try to run the script in MainActivity with code as follows:
onCreate() {
......
execScript();
}
execScript(){
try{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("sh /.../editXml.sh");
} catch(Throwable t)
{
t.printStackTrace();
}
}
The editXml.sh is in my local, but the code doesn't work when I run app in Android studio.(Works on local) Should I put my script in the app? And which part of the app? Any suggestion?
Try this. I've tested this code and it works.
Let's you script named script.sh.
Put file script.sh to you project's /res/raw folder.
Use code below.
Build apk. Unpack apk (this is usual zip-archive) and make sure file /res/raw/script.sh exists there.
Install apk on device and start it.
public static void executeCommandAndGetOutput(String command){
BufferedReader reader = null;
String result = "";
try {
Process p = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
if(reader != null)
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Log.i("Test", result);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String pathToScript = getDir("my_scripts", 0).getAbsolutePath() + File.separator + "script.sh";
// Unpacking script to local filesystem
InputStream in = getResources().openRawResource(R.raw.script);
FileOutputStream out = null;
try {
out = new FileOutputStream(pathToScript);
byte[] buff = new byte[1024];
int read = 0;
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
}
catch(Exception e){
}
finally {
try {
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Make script executable
executeCommand("chmod 775 " + pathToScript);
// Execute script
executeCommand("sh " + pathToScript);
}
public static String getSystemCommandOutput(String command){
BufferedReader reader = null;
String result = "";
try {
Process p = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null){
result += line + "\n";
}
p.waitFor();
} catch (Exception e) {
e.printStackTrace();
} finally {
closeQuietly(reader);
}
return result;
}
You can put script at raw resources and then unpack it to Context.getDir(...) folder and run from there with absolute path.
Also you need to run "chmod 775" (chmod +x) for this file before executing.
Example about copying a file from raw: Copying raw file into SDCard? You can copy to app folder (Context.getDir(...)) instead of sdcard
console output:
58:07.979 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ onCreate
12:58:08.234 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ PATH: /data/data/cc.softwarefactory.lokki.android/app_my_scripts/editxml.sh
12:58:08.258 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ result:
12:58:08.287 8935-8935/cc.softwarefactory.lokki.android E/MainActivity﹕ result: not found
I changed
Log.i("Test", result) to Log.e(TAG,"result: " + result);

How can I send the log file of the android device via email from inside my app?

as an error report I want to send the device and/or application log to a email account. For that I prepared a button in my view. Can someone help me with that, how can I retrieve the log files?
Thanks
String separator = System.getProperty("line.separator");
try {
Process process = Runtime.getRuntime().exec("logcat -d");
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
log.append(line);
log.append(separator);
}
} catch (Exception e) {
}
Here's a slightly improved version, adapted from Ramesh (thanks). The main difference is to do your own buffering. It's fast.
private void extractLogToFile()
{
// Make file name.
String fullName = ...;
// Extract to file.
File file = new File (fullName);
InputStreamReader reader = null;
FileWriter writer = null;
try
{
// get input stream
String cmd = "logcat -d -v time";
Process process = Runtime.getRuntime().exec(cmd);
reader = new InputStreamReader (process.getInputStream());
// write output stream
writer = new FileWriter (file);
char[] buffer = new char[10000];
do
{
int n = reader.read (buffer, 0, buffer.length);
if (n == -1)
break;
writer.write (buffer, 0, n);
} while (true);
reader.close();
writer.close();
}
catch (IOException e)
{
if (writer != null)
try {
writer.close();
} catch (IOException e1) {
}
if (reader != null)
try {
reader.close();
} catch (IOException e1) {
}
e.printStackTrace();
return;
}
}

Check to see whether root was granted?

I have set up my app to execute the su command using this code:
try {
Runtime.getRuntime().exec("su");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
altDialog.setTitle("No Root");
altDialog
.setMessage("I am afraid I have been unable to execute the su binary. Please check your root status.");
altDialog.setCancelable(false);
altDialog.setButton("Exit App",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
Log.e("Android .img Flasher",
"Exiting due to root error");
finish();
}
});
}
This catches if the su command doesn't exist (I believe), but not if root was actually granted.
How would I be able to check if root was actually granted?
On a side note, how would I be able to store the output of a command using the Runtime.getRuntime.exec() command?
You can use the code bellow. I've wrote it for generic command use, but it works with su command as well. It returns if the command succeed as well as the command output (or error).
public static boolean execCmd(String command, ArrayList<String> results){
Process process;
try {
process = Runtime.getRuntime().exec(new String [] {"sh", "-c", command});
} catch (IOException e) {
e.printStackTrace();
return false;
}
int result;
try {
result = process.waitFor();
} catch (InterruptedException e1) {
e1.printStackTrace();
return false;
}
if(result != 0){ //error executing command
Log.d("execCmd", "result code : " + result);
String line;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
try {
while ((line = bufferedReader.readLine()) != null){
if(results != null) results.add(line);
Log.d("execCmd", "Error: " + line);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return false;
}
//Command execution is OK
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
try {
while ((line = bufferedReader.readLine()) != null){
if(results != null) results.add(line);
Log.d("execCmd", line);
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
You call it with two arguments:
command - string with command to execute
results - empty ArrayList to return the command output. If null, output is not returned.
To check sucommand you can do the following:
//Array list where the output will be returned
ArrayList<String> results = new ArrayList<String>();
//Command to be executed
String command = "su -c ls";
boolean result = execCmd(command,results);
//result returns command success
//results returns command output
Regards.
public static boolean isRootAvailable(){
Process p = null;
try{
p = Runtime.getRuntime().exec(new String[] {"su"});
writeCommandToConsole(p,"exit 0");
int result = p.waitFor();
if(result != 0)
throw new Exception("Root check result with exit command " + result);
return true;
} catch (IOException e) {
Log.e(LOG_TAG, "Su executable is not available ", e);
} catch (Exception e) {
Log.e(LOG_TAG, "Root is unavailable ", e);
}finally {
if(p != null)
p.destroy();
}
return false;
}
private static String writeCommandToConsole(Process proc, String command, boolean ignoreError) throws Exception{
byte[] tmpArray = new byte[1024];
proc.getOutputStream().write((command + "\n").getBytes());
proc.getOutputStream().flush();
int bytesRead = 0;
if(proc.getErrorStream().available() > 0){
if((bytesRead = proc.getErrorStream().read(tmpArray)) > 1){
Log.e(LOG_TAG,new String(tmpArray,0,bytesRead));
if(!ignoreError)
throw new Exception(new String(tmpArray,0,bytesRead));
}
}
if(proc.getInputStream().available() > 0){
bytesRead = proc.getInputStream().read(tmpArray);
Log.i(LOG_TAG, new String(tmpArray,0,bytesRead));
}
return new String(tmpArray);
}

Categories

Resources