[Q] Writing to and reading from /data/local? - Android Q&A, Help & Troubleshooting

I am creating a little app that will let a user read what's in a certain textfile in /data/local, edit it, and then save it. I have gotten everything to work by using some tutorials here and there, but there's still something not working.
Root access has been achieved, and writing/reading the file is done too, but when pressing the "Write" button, I get a toast saying "open failed: EACCES (Permission denied)". Google unfortunately didn't help me much on this one. Also, I am using the WRITE_EXTERNAL_STORAGE permission.
Code:
Code:
package bas.sie.hai;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
public class DataLocalActivity extends SherlockActivity {
EditText txtData;
Button btnReadSDFile;
Button btnWriteSDFile;
Button btnReadSkipFile;
Button btnWriteSkipFile;
Button btnClearScreen;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Process p;
try {
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("echo \"Do I have root?\" >/system/sd/temporary.txt\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
try {
p.waitFor();
if (p.exitValue() != 255) {
// TODO Code to run on success
Toast.makeText(this, "root", Toast.LENGTH_LONG);
}
else {
// TODO Code to run on unsuccessful
Toast.makeText(this, "No root", Toast.LENGTH_LONG);
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
Toast.makeText(this, "No root", Toast.LENGTH_LONG);
}
} catch (IOException e) {
// TODO Code to run in input/output exception
Toast.makeText(this, "NO root", Toast.LENGTH_LONG);
}
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}
txtData = (EditText) findViewById(R.id.txtData);
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/move_cache.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading from SD: 'move_cache.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/move_cache.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing to SD: 'move_cache.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnReadSkipFile = (Button) findViewById(R.id.btnReadSkipFile);
btnReadSkipFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/skip_apps.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading from SD: 'skip_apps.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnWriteSkipFile = (Button) findViewById(R.id.btnWriteSkipFile);
btnWriteSkipFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/skip_apps.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing to SD: 'skip_apps.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
});
}// onCreate
}
Thanks in advance,
Bas

Dooder
1. Chaper 8. Have mercy on yourself.
2. coloredlogcat.py
3. why not
Code:
e.printStackTrace()
but
Code:
Toast.LENGTH_SHORT
is beyond me
4.
Code:
android.permissions.WRITE_EXTERNAL_STORAGE
does not equal permissions to write to
Code:
/data/local
5.
Google unfortunately didn't help me much on this one
Click to expand...
Click to collapse
Moment of honesty. G-FU sucks or you just gave up?
I am an a-hole for a reason here. All you need to know is out there. No one else will hit you harder on the head with a RTFM board than a coder.

el_bhm said:
Dooder
1. Chaper 8. Have mercy on yourself.
2. coloredlogcat.py
3. why not
Code:
e.printStackTrace()
but
Code:
Toast.LENGTH_SHORT
is beyond me
4.
Code:
android.permissions.WRITE_EXTERNAL_STORAGE
does not equal permissions to write to
Code:
/data/local
5.
Moment of honesty. G-FU sucks or you just gave up?
I am an a-hole for a reason here. All you need to know is out there. No one else will hit you harder on the head with a RTFM board than a coder.
Click to expand...
Click to collapse
The code is mostly from a tutorial, with a few edits. Why use stackTrace on a test? Also, I test on the device for reliability and root access. It's easier to see a Toast there, so didn't remove it.
About the Chapter 8: Yes, onClickListener is not the best way (skimmed over it, it's 1:26 AM here), but here too: optimizations later.
About Google: I Googled, didn't find anything that really could help me along so that I understood, asked in three other places. SO was someone who didn't reply later on, Google Groups said my permission was wrong, as I said WRITE_TO_EXTERNAL_STORAGE. I corrected that, saying I had the right permission but I wrote down the wrong one (hastily. Stupid, I know...), and here, on XDA, you're the only post yet. I have waited between posts to post it on all those boards, as I'm not an a**hole.
If any more information is needed, just tell me.
Bas
EDIT: Missed a bit. About the writing: I know now, it's just that I have no idea how to proceed from root access to writing there. And I do hope to learn how to do it.

1. You'd rather want to write into
Code:
/data/data/[package]/
Is there any particular reason you want to write directly to local? Some "system wide" app? From code I understand this is some tabbed app(?). Or is it just test for root?
Unless you have somewhat extensive knowledge of Linux and programming, don't go into root access. Make yourself a favour and get as much knowledge of objective programming first. It seems it was inspired by Outler doing root in part two. He's doing ADK in part 3. These are not easy things.
2. Are you sure you are writing anything? With this code I am getting nowhere actually.
I have not written anything with root (main reason it caught my attention). My best guess is though, permissions are not escalated for objects you are creating while setting up listeners for buttons.
From brief reading of the code and documentation it seems that you are escalating permissions for Process p which you works in conjunction with DataOutputStream. While setting up listeners you are not doing anything with p anymore.
My best guess permissions escalation would apply to the whole package, but as I see it, it does not happen.
EDIT: Besides, keep in mind you are writing a file via echoing through shell. Which is not equivalent of writing through instances of classes in onClickListeners
3. As to why printStackTrace()
Unless you are running Windows(which for Android development I really feel you should not) with coloredlogcat.py you'll have much more comprehensive output to troubleshoot the app. Line where problem occurs. Where it originates, where it goes, etc.
There should be some interpreter of python for Windows, but I don't know how the script will behave though.
4. Inserting logcat output is always helpful.
Providing the layout is always helpful.

el_bhm said:
1. You'd rather want to write into
Code:
/data/data/[package]/
Is there any particular reason you want to write directly to local? Some "system wide" app? From code I understand this is some tabbed app(?). Or is it just test for root?
Unless you have somewhat extensive knowledge of Linux and programming, don't go into root access. Make yourself a favour and get as much knowledge of objective programming first. It seems it was inspired by Outler doing root in part two. He's doing ADK in part 3. These are not easy things.
2. Are you sure you are writing anything? With this code I am getting nowhere actually.
I have not written anything with root (main reason it caught my attention). My best guess is though, permissions are not escalated for objects you are creating while setting up listeners for buttons.
From brief reading of the code and documentation it seems that you are escalating permissions for Process p which you works in conjunction with DataOutputStream. While setting up listeners you are not doing anything with p anymore.
My best guess permissions escalation would apply to the whole package, but as I see it, it does not happen.
EDIT: Besides, keep in mind you are writing a file via echoing through shell. Which is not equivalent of writing through instances of classes in onClickListeners
3. As to why printStackTrace()
Unless you are running Windows(which for Android development I really feel you should not) with coloredlogcat.py you'll have much more comprehensive output to troubleshoot the app. Line where problem occurs. Where it originates, where it goes, etc.
There should be some interpreter of python for Windows, but I don't know how the script will behave though.
4. Inserting logcat output is always helpful.
Providing the layout is always helpful.
Click to expand...
Click to collapse
The files I'm writing are supposed to be in /data/local. Writing anywhere else would obviously kind of defeat the purpose.
I don't really have knowledge of Linux, didn't know you had to to be able to write a file. On the other hand, I had basically no knowledge of Android when I started writing my first app, and that worked out quite well, if I do say so myself.
About the permissions for the writing: I think you are right about that. I simply followed a tutorial, added SU permission check, and changed the path. Then tried to get that working.
I am running Windows. I do have Ubuntu on a bootable USB and on my HDD, but on the stick it has a low res and doesn't save any configs (which is not that weird), and on my HDD it suddenly fails to boot, and WUBI won't let me uninstall...
Plus, too much fiddling. Why is it so hard to get Flash installed, for God's sake?
About the LogCat output: I'm not really one to hook my phone up to my PC for that, unless no other solution is possible. Not because I'm lazy, but because my PC generally takes a couple of minutes to recognize the phone, open Explorer, etc. when I am doing a couple of other things.
I guess I'll just give up. Do you have any sites/places where I can gain some valuable knowledge about this?
Bas

About that permission check. Well, it passes the test. Thing is, there is no
Code:
/system/sd/temporary.txt
after I drop to adb shell.
Is that path the one you had set? IIRC Samsung does something funky with internal/external memory mounts in their devices. Is that path valid at all?
I'm guessing echo fails but passes the su test. So permissions are good, it seems.
Theoretically you can try parsing contents you need to that command you are basically executing. If there is a file in
Code:
/system/sd/
You could write file you need as temps wherever you have rights, then gain permissions and copy the contents via
Code:
cat [path_to_temp_file] > /data/local/file
Going offtopic.
Never. Ever use WUBI. Seriously. Just read about install process. If it fails on normal CD, download alternate. A bit more daunting but still should be manageable. Or get other distro like Mint.
It's enough to copy file to
Code:
~/.mozilla/plugins
. FF and Opera should easily use it.
Or just install
Code:
ubuntu-restricte-extras
. It should have flash.
You can also get to your phone over wifi. Just get adbWireless from market.
Knowledge? On what?
Programming? Read documentation of android. Many tutorials. Really easy to read (compared to other OS docs), extensively described.
Stackoverflow
Get any O'reily books.
Android? See above.
Linux? Stop expecting from any distro to behave like Windows and use it as you would know nothing about PC. You'll save yourself much time and frustration.
webup8, omgubuntu, planet-ubuntu. Enough there to start.

el_bhm said:
About that permission check. Well, it passes the test. Thing is, there is no
Code:
/system/sd/temporary.txt
after I drop to adb shell.
Is that path the one you had set? IIRC Samsung does something funky with internal/external memory mounts in their devices. Is that path valid at all?
I'm guessing echo fails but passes the su test. So permissions are good, it seems.
Theoretically you can try parsing contents you need to that command you are basically executing. If there is a file in
Code:
/system/sd/
You could write file you need as temps wherever you have rights, then gain permissions and copy the contents via
Code:
cat [path_to_temp_file] > /data/local/file
Going offtopic.
Never. Ever use WUBI. Seriously. Just read about install process. If it fails on normal CD, download alternate. A bit more daunting but still should be manageable. Or get other distro like Mint.
It's enough to copy file to
Code:
~/.mozilla/plugins
. FF and Opera should easily use it.
Or just install
Code:
ubuntu-restricte-extras
. It should have flash.
You can also get to your phone over wifi. Just get adbWireless from market.
Knowledge? On what?
Programming? Read documentation of android. Many tutorials. Really easy to read (compared to other OS docs), extensively described.
Stackoverflow
Get any O'reily books.
Android? See above.
Linux? Stop expecting from any distro to behave like Windows and use it as you would know nothing about PC. You'll save yourself much time and frustration.
webup8, omgubuntu, planet-ubuntu. Enough there to start.
Click to expand...
Click to collapse
Well, this is intended for AOSP ROMs, so I was thinking that there shouldn't be any problem in trying to write a file in that directory. But yes, Samsung does do some weird things...
About the copying and then moving from there: Might be a good idea if I can figure it out. However, do you think that will suddenly work?
The install at first was planned to be from the bootable stick I have, but when I read about WUBI, it seemed so easy. Easy to deinstall Ubuntu, too. Anyhow, I think a friend kind of borked it not too long ago. Pressed the wrong button somewhere, might have slightly affected the MBR (Windows boot animation is also gone now, back to Vista ).
Could you explain a bit more about the Flash install? It seemed (and truly was) so tedious at the time for something that was still slow and laggy... In my experience, don't get me wrong.
I have used AirDroid for example for reaching my phone, good suggestion there.
On the topic of developing (circling back around ), I will be looking into your suggestions. I do use Google and tutorials a lot, and SO has been quite a good help in that. Also, asking people to help personally (GTalk, for example, or PM on a forum), has got me quite a long way.
And using Ubuntu like I know nothing: It was quite different . I noticed that almost all of my knowledge was rendered useless in a matter of minutes haha. Bad thing is I did still think I knew, I guess. Led to frustration over it being so annoying. I guess it takes a lot of getting used to.

If that "temporary.txt" file is created, I don't see why it should fail since it passes the Root check.
instead of
Code:
cat
you may as well use
Code:
cp
which is basically command for copy.
About Flash (on which even Adobe is dropping a ball since they have balls to finally admit it's a joke anyway) you can read here.
https://help.ubuntu.com/community/RestrictedFormats
Alternate version of installer never failed me so far.

el_bhm said:
If that "temporary.txt" file is created, I don't see why it should fail since it passes the Root check.
instead of
Code:
cat
you may as well use
Code:
cp
which is basically command for copy.
About Flash (on which even Adobe is dropping a ball since they have balls to finally admit it's a joke anyway) you can read here.
https://help.ubuntu.com/community/RestrictedFormats
Alternate version of installer never failed me so far.
Click to expand...
Click to collapse
I'll take a look at using cp. However, it might be some time before I pick this up again. My earlier project has almost been accepted by the person who asked me to make it, so first I'll be busy on that.
But the basic thing here is to create it somewhere else and copy it, right? Let's hope that works, then .
Also, I'll be looking at your suggestions for Flash and the alternate installer, thanks a lot!

Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums & Read the Forum Rules
Moving to Q&A

Related

Help with App and shell script integration

I have an app I have written with the help of another user on the forum here. It currently executes shell scripts that are located in the /system/bin directory.
Is there a way to add these scripts to an assets directory within the app and call on them from list view strings?
flappjaxxx said:
I have an app I have written with the help of another user on the forum here. It currently executes shell scripts that are located in the /system/bin directory.
Is there a way to add these scripts to an assets directory within the app and call on them from list view strings?
Click to expand...
Click to collapse
You can add anything to the "assets" directory in your project and it will be stored as-is in the apk; however, you'll need to extract it and place it somewhere to be able to use it. "res/raw" is another place you can add raw resources. Your main activity should check to see if you're scripts exist and if not, extract and copy them to a directory owned by your apk (like "/data/data/com.example.myprog/shell-scripts"). Create a function in your class and call it from the main activity in OnCreate(). Add a function something like this:
Code:
protected void CheckAndCopyScript() {
// check if it's already there
File myscript = new File("/data/data/com.example.myapp/scripts/script.sh");
if (myscript.exists()) {
// already there, nothing to do.
return;
}
//create the directory
Process p1 = Runtime.getRuntime().exec("sh");
DataOutputStream os1 = new DataOutputStream(p1.getOutputStream());
os1.writeBytes("mkdir /data/data/com.example.myapp/scripts/\n");
os1.writeBytes("exit\n");
os1.flush();
//open the raw resource
InputStream scriptStream = getResources().openRawResource(R.raw.myscript);
try {
byte[] bytes = new byte[scriptStream .available()];
DataInputStream dis = new DataInputStream(scriptStream );
dis.readFully(bytes);
//create the new script file
FileOutputStream scriptOutStream = new FileOutputStream(
"/data/data/com.example.myapp/scripts/script.sh");
scriptOutStream .write(bytes);
scriptOutStream .close();
// set executable permissions on the script
Process p2 = Runtime.getRuntime().exec("sh");
DataOutputStream os2 = new DataOutputStream(p2.getOutputStream());
os2.writeBytes("chmod 755 /data/data/com.example.myapp/scripts/script.sh\n");
os2.writeBytes("exit\n");
os2.flush();
} catch (Exception e) {
//show the exception
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
return;
}
}
Thanks for the info. I will try this soon when I am jot so sick and hopefully you won't mind if I pock your brain a bit if I run into issues.
Sent from A Van Down By The River!
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A
lufc said:
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A
Click to expand...
Click to collapse
Sorry about that total brain cramp apparently on my part

Need help troubleshooting my code.

Ok so for these last three days i have been trying to get into the android game. I did the hello android tutorial and yea. that was boring lol, so i decided to try and create a program to temporarily fix the keyboard backlight issue being experienced by some ICS port users. i have only part of the code done but it does not execute at all. I am not sure whats the problem. I have writted additional pieces to this code but have not put them in the program as i want to figure out why it doesnt run before i add more and then clean it up.
Code:
package com.dri94.led;
import java.util.*;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class LEDLightActivity extends Activity {
/** Called when the activity is first created. */
@SuppressWarnings("null")
@Override
public void onCreate(Bundle savedInstanceState) {
final int SDK_INT;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Scanner input = new Scanner(System.in);
DataOutputStream os = null;
TextView tv = new TextView(this);
tv.setText("Enter 'y' to turn on keyboard light or 'n' to turn it off");
String yOrN = input.next();
if (yOrN == "y") {
tv.setText("Enter SDK number 7 for GB devices or 14 for ICS devices. No other devices are supported at this time");
SDK_INT = input.nextInt();
if (SDK_INT == '7') {
try {
os.writeBytes("echo 255 > /sys/class/leds/keyboard-backlight/brightness\n"
+ "chmod 444 /sys/class/leds/keyboard-backlight/brightness\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
try {
os.writeBytes("echo 255 > /sys/class/leds/kpd_backlight_en\n"
+ "chmod 444 /sys/class/leds/kpd_backlight_en\n");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
Any logcat output? I don't have ICS so those paths aren't available on my device, but similar paths are symlinks and directories. Does your app have write permissions to kpd_backlight_en (or whatever the symlink points to)?
You have a lot of problems there, lets point some of them out,
Code:
DataOutputStream os = null;
Youre initializating your outputStream as null, wich is a problem consideering you use it for writing a file. Also there are so many easier ways to write files, for example, I propose this simple writing method
Code:
public static void WriteFile(String text, String file) {
try{
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
out.write(text);
out.close();
}catch (Exception e){
//Deal exception ;D
}
}
simple code usage will be then
Code:
WriteFile("255", "/sys/class/leds/keyboard-backlight/brightness");
Second error I found, comparing strings with "==", this
Code:
if (yOrN == "y")
is wrong, you should try with
Code:
if (yOrN.equals("y")) {
Another thing i dont understand is this
Code:
final int SDK_INT;
Why do you declare a variable as final, if you are gonna assign some value later, right here
Code:
SDK_INT = input.nextInt();
Last thing I found is also comparing an integer with string? I dont understand what you do there
Code:
if (SDK_INT == '7')
Also your way to manage user inputs would be better with a simple button (or toggleButton) for turn on/off lights, or even use SensorEventListener.
I hope I have helped you in some , just tell me if you need something. Good luck!
How should i initialize it? And thank you alot. Ima play with my code tomorrow. The last one though is comparing it with a character value. but this post helped alot. I appreciate it... Especially cause i made soooo many beginner mistakes. My professor would be disappointed
Sent from my XT862 using T
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A
thanks i wasnt sure where to post this! ill remember that from now on

Ping app

hey guys,
Building an app that runs a ping command at the moment and I can't quite get it to work. If I modify the command to something that isn't a terminal command then it'll output my error statement but i can't get it to display the ping output. any help would be awesome. I know my outputs for my error are bad but it's an easy way to determine what path it's outputting.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.lang.Process;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView Text = new TextView(this);
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.getRuntime().exec("system/bin/ping 192.168.1.1");
BufferedReader in = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line = "null";
while ((line = in.readLine()) != null) {
Text.setText(in.readLine());
}
}
catch (Exception e)
{
String line="55";
Text.setText(line);
}
setContentView(Text);
}
}
Thanks for any help you guys can give me,
Adam
Hey,
Try using "system/bin/ping -c 1 192.168.1.1" instead.
And then add this line just after that:
Code:
proc.waitFor();
and while reading the output of the ping you might want to do it like this maybe?
Code:
String line = "";
String result = "";
while (line != null)
{
result = result + "\n" + line;
line = in.readLine();
}
Text.setText(result);
If you want to ping more than 1 packet I think it would be better to make a new thread and do proc.waitFor() in that thread. Then send a message using a handler to set the output of the ping to the TextView
k i have done that and that does make more sense but Im still getting a black screen on the output. i am testing on a Sony tab s and using AIDE (on the device) cause my eclipse is broken. this is how my code looks now,
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.io.*;
import java.lang.Process;
public class MainActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
TextView Text = new TextView(this);
Runtime runtime = Runtime.getRuntime();
try
{
Process proc = runtime.getRuntime().exec("system/bin/ping 192.168.1.1");
BufferedReader in = new BufferedReader(
new InputStreamReader(proc.getInputStream()));
String line = "null";
while ((line = in.readLine()) != null) {
Text.setText(in.readLine());
}
}
catch (Exception e)
{
String line="55";
Text.setText(line);
}
setContentView(Text);
}
}
Is there anything else I could be missing??
Thanks,
Adam
Hey, I think you posted the same code again.
I am not sure if you can read the process stream before it is complete and ping does take a long time to complete. So your main thread is blocking on it and it doesn't get to executing the setContentView.
Thats why I think going for a seperate thread is a better option.
so it would be better to put the ping into a new class and call on it when i need it??
Not a seperate class, a seperate thread to be more specific.
Even if you do put the ping code in a seperate class' method and call that method in onCreate it will still run on the your applications main thread.
What I was trying to say is something along the lines of the following code:
Code:
private TextView textView;
private Process process;
private Handler handler;
private Thread pingThread;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
textView.setText("Pinging...");
setContentView(textView);
try
{
process = Runtime.getRuntime().exec("system/bin/ping -c 5 192.168.1.1");
handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
String result = "";
while(line != null)
{
result = result + "\n" + line;
line = reader.readLine();
}
reader.close();
textView.setText(result);
}
catch(Exception e)
{
e.printStackTrace();
textView.setText("Error");
}
}
};
pingThread = new Thread()
{
@Override
public void run()
{
try
{
process.waitFor();
}
catch(Exception e)
{
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
};
pingThread.start();
} catch (Exception e)
{
e.printStackTrace();
}
}
I am not sure if this is exactly how you want your app to behave. There might be a better way of doing what you want than what I have suggested but I tested the above code and it works for me.
thats wicked, basically what want my program to do is to run a ping command through a usb to rj45 adapter. at the moment I just need it to do the ping command through wifi and once that was working I was going to set it up to go through usb.
I wonder if there's something I'm doing wrong like I'm build the apk in AIDE on the tablet or something, cause I'm still getting a black screen when booting the app.
If I error the code up a bit, Like put "system/bin/pi ....." instead I do get pinging on the app but no error output and if the code is fine then nothing displays
That is very strange :S.
If you use the incorrect command it works fine but when you use the correct command it doesn't?
Can you post your code? or provide more details if possible?
the code is just the code you posted cause I thought if a I could get it working with that code then modify it to what it needs to do, when the command is incorrect it displays "ping....." but doesn't display an error, I'm going to install eclipse and build the package with that and see how it goes. did you test on a tablet and what did you use to deploy the package?
Adz117 said:
the code is just the code you posted cause I thought if a I could get it working with that code then modify it to what it needs to do, when the command is incorrect it displays "ping....." but doesn't display an error, I'm going to install eclipse and build the package with that and see how it goes. did you test on a tablet and what did you use to deploy the package?
Click to expand...
Click to collapse
I think i know whats happening. It isnt the Ide and using eclipse wont make much of a difference.
Are you usIng something like -c 5 in the ping command? Cause if you aren't i think ping is Going to take a really long time and all you'll see on the screen is "Pinging..."
Yea I have got that in the command, when the code is correct and working I dont get anything all I get is a black screen. Its when I error the command up a bit that I get pinging
Sent from my Sony Tablet S using XDA
hey guys,
just got eclipse running and tested it on an avd emulator and it runs perfect, so the question is what would cause it not to run on my tablet?
I have no idea! I don't have access to an Android Tablet, so I can't test it out! I tested it out on my phone too and it works just fine.
One thing I can suggest though is:
Put log statements throughout the program to signify where the the control has reached. Then run it on your tablet. That should shed some light on where the code is failing on your tablet.
tested it on my phone which is running 2.3 and it failed on there as well, "ping......" would pop up for about a second then disappear, also if I use a command like ls instead of ping on my tablet it will work perfectly fine so I'm guessing for some reason past android 2.1 it doesn't like the ping command. any ideas?
I tested it out on phone with 2.2. Did you try putting log statements and checking where it is failing.
You could also add breakpoints in your code and run it?

[Q] How I can copy/modify files in /etc folder?

Hi, I'm trying to use the library RootTools to make root operations on android system. I want to make a backup of some files including in the /etc folder with the next commands:
Code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File exists = new File("/etc/gps.conf");
if (exists.exists()) {
// We make a backup first
int date = (int) System.currentTimeMillis();
String source = "/etc/gps.conf";
String destination = "/etc/gps" + date + ".conf";
RootTools.copyFile(source, destination, true, true);
// Last time that file was modified
// Date filedate = new Date(exists.lastModified());
}
}
});
It's supposed that with the RootTools.copyFile I can make that operation, but It doesn't make anything. I see that in cat /proc/mount doesn't appear etc folder. I'm tried too with the Apache transfer file copy, FileUtils.copyFile(source, destination) but it seems that it have problem with the mount system, who seems to be in RO. I try too with RootTools.remount("/etc", "RW") but fails too.
I'm lost with this issue. Pleeeeeease give some advices!!! I want to know how I can edit, create, delete, modify files in /etc /data... etc.
I'm testing this on a Samsung Galaxy S3 with an stock rom 4.1.2.
Thanks for your advices.
rumbitas said:
Hi, I'm trying to use the library RootTools to make root operations on android system. I want to make a backup of some files including in the /etc folder with the next commands:
Code:
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File exists = new File("/etc/gps.conf");
if (exists.exists()) {
// We make a backup first
int date = (int) System.currentTimeMillis();
String source = "/etc/gps.conf";
String destination = "/etc/gps" + date + ".conf";
RootTools.copyFile(source, destination, true, true);
// Last time that file was modified
// Date filedate = new Date(exists.lastModified());
}
}
});
It's supposed that with the RootTools.copyFile I can make that operation, but It doesn't make anything. I see that in cat /proc/mount doesn't appear etc folder. I'm tried too with the Apache transfer file copy, FileUtils.copyFile(source, destination) but it seems that it have problem with the mount system, who seems to be in RO. I try too with RootTools.remount("/etc", "RW") but fails too.
I'm lost with this issue. Pleeeeeease give some advices!!! I want to know how I can edit, create, delete, modify files in /etc /data... etc.
I'm testing this on a Samsung Galaxy S3 with an stock rom 4.1.2.
Thanks for your advices.
Click to expand...
Click to collapse
Simply mount system as read/writeable
Sent from my LT18i using xda premium
exquisite.nish said:
Simply mount system as read/writeable
Sent from my LT18i using xda premium
Click to expand...
Click to collapse
This is the problem. The third parameter of RootTools.copyFile(source, destination, true, true) enable the RW option of the folder before the copy. The problem is that it doesn't change the mount type, still RO, still when I try RootTools.remount("/etc/", "rw").
I want to know if there is another way to do that.
Thanks.

[MOD][KK][XPOSED] KitKat SD Card Full Access

This module fixing external SD card write issue on Android 4.4 KitKat. Module does not have any setting activity. Just enable it in Module tab and restart your phone.
No need to patch platform.xml file.
http://repo.xposed.info/module/kz.virtex.android.sdcardfix
Can be downloaded in Xposed Download tab.
HOW IT WORKS and WHAT FOR?
KitKat No SD card access
If SD card write access not enabled, then no any application without root permission can operate with files on SD Card.
KitKat WITH SD Card access
Once mod is enabled - any application without root access can operate with files on SD, including move, copy, delete.
Source code for other developers
Code:
/*
The MIT License (MIT)
Copyright (c) 2014 by Nurlan Mukhanov aka Falseclock
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package kz.virtex.android.sdcardfix;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
public class XMain implements IXposedHookZygoteInit
{
@Override
public void initZygote(StartupParam startupParam) throws Throwable
{
final Class<?> pms = XposedHelpers.findClass("com.android.server.pm.PackageManagerService", null);
XposedHelpers.findAndHookMethod(pms, "readPermission", "org.xmlpull.v1.XmlPullParser", "java.lang.String", new XC_MethodHook()
{
protected void afterHookedMethod(MethodHookParam param) throws Throwable
{
String permission = (String) param.args[1];
if (permission.equals("android.permission.WRITE_EXTERNAL_STORAGE")) {
Class<?> process = XposedHelpers.findClass("android.os.Process", null);
int gid = (Integer) XposedHelpers.callStaticMethod(process, "getGidForName", "media_rw");
Object mSettings = XposedHelpers.getObjectField(param.thisObject, "mSettings");
Object mPermissions = XposedHelpers.getObjectField(mSettings, "mPermissions");
Object bp = XposedHelpers.callMethod(mPermissions, "get", permission);
int[] bp_gids = (int[]) XposedHelpers.getObjectField(bp, "gids");
XposedHelpers.setObjectField(bp, "gids", appendInt(bp_gids, gid));
}
}
});
}
private static int[] appendInt(int[] cur, int val)
{
if (cur == null) {
return new int[]
{ val };
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
return cur;
}
}
int[] ret = new int[N + 1];
System.arraycopy(cur, 0, ret, 0, N);
ret[N] = val;
return ret;
}
}
Advantage against HandleExternalStorage: http://forum.xda-developers.com/xposed/modules/app-handleexternalstorage-t2693521 ?
Did not know that there was already such a fix available. Just found this one and since it is activated I have much less lags. Seems there were many apps trying to access Sdcard causing lags. Awesome!
Sent from my GT-I9300 using XDA Premium 4 mobile app
Can you share source code?
pyler said:
Can you share source code?
Click to expand...
Click to collapse
yep!
see first post
defim said:
Advantage against HandleExternalStorage: http://forum.xda-developers.com/xposed/modules/app-handleexternalstorage-t2693521 ?
Click to expand...
Click to collapse
oops. tried to search something with "SD" word in repository and didn't find anything.
thought nobody still implemented such mod.
Just downloaded module, decompiled and compared with my version.
I think my method works much more correct and less battery power consumptive. I only hooking internal android packages at startup, while module above doing this with every application.
Falseclock said:
oops. tried to search something with "SD" word in repository and didn't find anything.
thought nobody still implemented such mod.
Just downloaded module, decompiled and compared with my version.
I think my method works much more correct and less battery power consumptive. I only hooking internal android packages at startup, while module above doing this with every application.
Click to expand...
Click to collapse
Awesome! Thanks for source!
Falseclock said:
I think my method works much more correct and less battery power consumptive. I only hooking internal android packages at startup, while module above doing this with every application.
Click to expand...
Click to collapse
No. Mine gives extra battery power
The funny thing is that both are 99% the same, the only difference is appendInt()
defim said:
No. Mine gives extra battery power
The funny thing is that both are 99% the same, the only difference is appendInt()
Click to expand...
Click to collapse
That's good if so! :good:
do you know alternative to com.android.internal.util.ArrayUtils? Not to use internal API...
pyler said:
do you know alternative to com.android.internal.util.ArrayUtils? Not to use internal API...
Click to expand...
Click to collapse
Code:
public static int[] appendInt(int[] cur, int val) {
if (cur == null) {
return new int[] { val };
}
final int N = cur.length;
for (int i = 0; i < N; i++) {
if (cur[i] == val) {
return cur;
}
}
int[] ret = new int[N + 1];
System.arraycopy(cur, 0, ret, 0, N);
ret[N] = val;
return ret;
}
Is this module necessary for CM11 too? Sorry for noob question
Edit: Got it. Its not needed
Does this also fix the option of deleting SD files through regular file explorers and apps?
Abu-7abash said:
Does this also fix the option of deleting SD files through regular file explorers and apps?
Click to expand...
Click to collapse
12k downloads and no any complain
Just bought a sd card 64 gb samsung EVO , and i have no problem with full acces , copy/erase/moving apps , without installing this module , so , for what is useful this mod ???
Doesn't work for me :^(
Neither this nor the other xposed app mentioned in this thread work for me. Installed the app, marked it active, rebooted (just like I do with any xposed module) and still my apps can't touch the SD space.
Any thoughts or ideas anyone?
Samsung Galaxy Note 10.1 (2014 Edition)
SM-P600
Android 4.4.2
Build KOT49H.P600UEUCND2
i face also the same problem. Xperia Z2 here (latest version, Rooted), i have installed / reboot the module, but doesn't let me to move apps to my SD.
Is there any viable solution?
Ty in advance
Doesn't work on Note 3 AT&T.
Sent from the Phantom Drive on Krypton.
What exactly does this module do?
HunterNIU said:
Neither this nor the other xposed app mentioned in this thread work for me. Installed the app, marked it active, rebooted......
Click to expand...
Click to collapse
@Falseclock, same here.....using Xolo Q3000 device with Stock Rooted Android v4.4.2. used this app. (i just hope this is not deemed off-topic here....)
i'm trying to use onandroid v9.51 to create nandroid backups while the device is running. see pics of command output and also platform.xml.
i even tried making changes to /mnt/media_rw like in the pic below (right). still, no go!
any idea why the file system remains read-only? please suggest a workaround or alternate methods. i'm not knowledgeable enough.
many thanks in advance. :fingers-crossed:

Categories

Resources