I'm calling C code by JNI in android app.
Every thing is OK in calling, but when I put this code:
FILE* fp = fopen("/storage/sdcard0/input.txt","w+");
if(fp==NULL)
return(*env)->NewStringUTF(env,"n");
else
return(*env)->NewStringUTF(env,"y");
it gets "n". I'm sure that the path is true and I tried this command on my mobile's terminal:
cat /storage/sdcard0/input.txt
and it got me the file's contents.
Edit:
I tried to change the permission of the file by this code but it gave me the same response:
void changePerm()
{
Process chperm;
try {
chperm=Runtime.getRuntime().exec("su");
DataOutputStream os =
new DataOutputStream(chperm.getOutputStream());
os.writeBytes("chmod 777 /storage/sdcard0/input.txt\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
chperm.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I also add this permission and no thing changed:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I take it that the permissions on the file are in fact 0777.
You added android.permission.READ_EXTERNAL_STORAGE, but you try to open for writing
FILE* fp = fopen("/storage/sdcard0/input.txt","w+");
You can get the error by checking for errno and get a message with strerror.
You must either open the file for reading only "r" or add permission for writing WRITE_EXTERNAL_STORAGE
Related
Hello I have been looking for ways to delete or rename an specific file in the internal storage of the cellphone. Specifically my targets are the files in the waze folder, that are in the root folder of the internal storage. As I said, I look for more information about this but nothing works for me, so I think that my error might be in the path i'm using. Here is my code:
TO RENAME:
file_Path = "/data/data/waze"
File from = new File(file_Path, "currentFileName");
File to = new File(file_Path, "newFilename");
from.renameTo(to); //this method returns me False
TO DELETE:
file_Path ="/data/data/waze/file"
File file = new File(file_Path);
boolean deleted = file.delete();
I try a lot of ways to do this, but this is the one I think is near to get it. So If anyone of you could point me my mistake/s I would thank you! A hug from Costa Rica!
You do not have read or write access to files on internal storage other than your own app's files. You cannot rename or delete files from another app, such as Waze.
The exception is that on rooted devices, you can ask to fork processes with superuser privileges, and those processes would have device-wide read/write access.
For completing #CommonsWare answer, you can check if the device is rooted, then do the methods or something else.
Here is an example,
Taken from : http://www.stealthcopter.com/blog/2010/01/android-requesting-root-access-in-your-app/
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
toastMessage("root");
}
else {
// TODO Code to run on unsuccessful
toastMessage("not root");
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
toastMessage("not root");
}
} catch (IOException e) {
// TODO Code to run in input/output exception
toastMessage("not root");
}
Or you can take a look at :
http://su.chainfire.eu/#how
https://github.com/Chainfire/libsuperuser
and also, use the following permission in your manifest too:
<uses-permission android:name="android.permission.ACCESS_SUPERUSER" />
Or a good example is available on Github:
https://github.com/mtsahakis/RootChecker
code snippet
void takeSnapShot()
{
Process process = null;
try
{
process = Runtime.getRuntime().exec("/system/bin/screencap -p /sdcard/snapshot/test_2.png" );
try
{
process.waitFor();
} catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I am gettin an empty file saved whereas If i use the same command through adb shell, i get my screen captured.
Any help will be appreciatable
Edit: my previous answer was mistaken, any app can use the screen capture command.
It might be a permission issue. Are you sure you have permission to write to sdcard?
Check this post, which covers your topic:
How to run android system app without root permisson?
I solved this by adding the following permission to my Manifest.
<uses-permission
android:name="android.permission.READ_FRAME_BUFFER"
tools:ignore="ProtectedPermissions"/>
NOTE: This is a protected permission, my application is a system app and also signed using the platform key.
I'm using Root Tools and I'm not getting too far with it...
I want to have access to delete files from /system/app and other directories that require root. I would love to do it programmatically through Java, but if I can do it through shell commands, that's OK. Too. My phone is rooted. Here's what I've tried so far.
RootTools.remount("/system", "rw");
try {
RootTools.sendShell("rm /system/app/Videos.apk", -1);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (RootToolsException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (TimeoutException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I've also tried:
public static void sendShell(List<String> cmds) throws Exception {
Process process = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(process.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd+"\n");
}
os.writeBytes("exit\n");
os.flush();
os.close();
process.waitFor();
}
I have no idea what to do from here...
Based on our conversations it looks like you need a different rom as there were issues remounting partitions on your device.
I would bet that flashing a new rom would alleviate this issue and allow RootTools to properly remount /system as rw and allow you to delete your file.
I am trying to execute shell command through my code for adding entry in Iptables. The following is my piece of code
private void createShellCommand(String uidValue_param, String interface_param) {
// TODO Auto-generated method stub
StringBuilder cmdScript=new StringBuilder();
script.append("iptables -A OUTPUT " + interface_param + "-m owner --uid-owner " + uidValue_param + "-j REJECT");
writeIptables(cmdScript);
}
private void writeIptables(StringBuilder scriptfile) {
// TODO Auto-generated method stub
String cmd=scriptfile.toString();
if(RootTools.isRootAvailable())
{
Process exec;
try {
exec = Runtime.getRuntime().exec(new String[]{"su","-c"});
final OutputStreamWriter out = new OutputStreamWriter(exec.getOutputStream());
out.write(cmd);
// Terminating the "su" session
out.write("exit\n");
out.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("IPtables updation failed", "Iptable write failed"+e);
}
}
else
{
Log.e("Root Access denied", "Access Denied");
}
}
Here there are two methods i.e, createshellCommand() for building the shell command and writeIptables() for updating the iptables. But whenever I run the program logcat is displaying the following warning
"W 19913 su request rejected (0->0 /system/bin/sh)"
But I can manually add the entry through command prompt and its adding to the iptables but by using the above code its not updating. My phone is rooted and I am using android 2.3.4 with linux kernel 2.6.29. And I am using external library "Roottools" for checking the root access.
Please help me to rectify the error.
This Works:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
execute_reboot();
}
void execute_reboot()
{
Process reboot;
try {
reboot=Runtime.getRuntime().exec("su");
DataOutputStream os =
new DataOutputStream(reboot.getOutputStream());
os.writeBytes("reboot\n");
os.flush();
os.writeBytes("exit\n");
os.flush();
reboot.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This Code Works fine. There are couple of small mistakes in your program. Try the one i pasted. Its working charm. All the best. I kept it as simple as possible so that it is easy to understand. You can still use arrays and other stuff to fancy your coding.
And yaa the same one also works for chmod command where you need to pass more than one argument.
For this Just replace
"os.writeBytes("reboot\n");"
with
"chmod 777 /dev/video0\n"(or any other system file).
Thanks. LEt me know if there is something tat i can do.
public static void rebootNow() {
Log.d(TAG, "Rebooting");
try {
#SuppressWarnings("unused")
Process proc = Runtime.getRuntime().exec(
new String[] { "su", "-c", "reboot" });
} catch (Exception ex) {
Log.d(TAG, "Rebooting failed (Terminal Error)");
}
}
This one is a little more compact
You can add "proc.waitFor();" after the Process proc... line to get rid of the unused warning, but rebooting your device takes a few seconds time and if you want to disable some features during the few seconds in your UI-thread, I think its better to not wait for the process to end.
Trying using the iptables command (with sudo and without), rather than just clobbering the iptables config file.
I am trying to create a file ,if it doesnot exist and tried to write some data to it. The same program I did in java, it was running fine.But when I try to do the same thing in Android I am getting NullPointerException at the place where I am trying to write data to file. And also, I did not find any new file in the current directory .I will share the code here:
xmlpoc.java
public class xmlPoc extends Activity {
String s="<employee>"+
"<details>"+
"<pictag id="+
"\"#drawable/icon\"" +
"mystr"+
"="+
"\"Picture 1\"" +
"myint" +
" =" +
"\"33\"" +
"/>"+
" <name>SandeepKumarSuman</name>"+
"<designation>J2ME Programmer</designation>"+
"<city>Gorakhpur</city>"+
"<state>UP</state>"+
"<name>mohan</name>"+
"<designation>J2ME GAMEProgrammer</designation>"+
"<city>HYD</city>"+
"<state>AP</state>"+
"<name>hari</name>"+
"<designation>Fresher</designation>"+
"<city>GNT</city>"+
"<state>AP</state>"+
"</details>"+
"</employee>";
File f;
FileOutputStream fop;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
f=new File("./myfile1.txt");
try {
fop=new FileOutputStream(f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("New file myfile.txt has been created to the current directory");
}
try {
fop.write(s.getBytes());
fop.flush();
fop.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Can anyone help me in sorting out this issue.
Thanks in Advance,
}
Check out the android dev guide here, and if you want to write to the external storage you should add the permissions to your manifest and use "getExternalStorageDirectory()", or "getExternalFilesDir()" if you are using API 8 or higher. You can't just write everywhere, that's why you need to use androids "openFileOutput(" or just write to the external storage.
External storage permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Try f=new File("myfile1.txt");