Change file permission in application

2019-04-09 17:49发布

问题:

I try to change file permission in application. Code is below:

Runtime.getRuntime().exec("chmod 777 /sdcard/test.txt");

This code NOT works in my application, but no error log. I also checked the shell tools under /system/bin, find chmod is under /system/bin, but some other info shown that chmod > toolbox. I am not clear about this. My application has used android:sharedUserId="android.uid.system". How to run this code or how to change permission of file? Thanks a lot.

回答1:

Runtime rt = Runtime.getRuntime();
Process proc;
try {
    proc = rt.exec(new String[] { "su", "-c", "chmod 777 " + Constants.filename });
    proc.waitFor();
} catch (Exception e){ //DOSTUFFS }

This should do the trick



回答2:

You've used the path /sdcard/ in your test -- is your SD Card formatted with a filesystem that supports standard Unix permissions? (FAT does not.)

You did not give an explicit path to chmod(1) in your string -- are you certain that chmod(1) is:

  • available on your device
  • available with your current PATH environment variable setting?

You can only change the permissions on files you own; are you certain that whatever your application's effective userid is owns the file on the SD card?

Lastly, Android may have additional security restrictions on changing file permissions. I don't know Android well, but perhaps changing file permission bits requires entries in the manifest declaring the operations, perhaps changing file permissions can only be done through provided APIs.



标签: android shell