How to save files to Android /system directory?

2019-04-02 03:32发布

问题:

I am writing an application that will copy files from its assets directory to the Android's /system directory.

I feel that I am getting close to achieving this, but I am not quite there. Here is the strategy that I have attempted:

First, I tried to change the permissions of the /system directory by:

Runtime.getRuntime().exec("su");
Runtime.getRuntime().exec("mount -o rw,remount -t yaffs2 /dev/block/mtdblock4");
Runtime.getRuntime().exec("chmod -R 777 /system");

Second, I tried to write a file to the /system directory.

I read that by remounting the directory, I could write files to it. Indeed, this seemed to work with a terminal. But in the application, I couldn't figure out how to make sure each command was completed before execution of the next one.

Does anyone have any suggestions?

回答1:

I assume there is a return value from the exec() method that you should be checking to see if the execution worked fine.

But I think you've got several mistakes in your attempts to execute this series of commands:

  • su can only influence its own process and child processes. You execute it with no arguments, so it does nothing. The next exec() method starts over from scratch with the exact permissions of your process, not the elevated privileges you might expect.
  • Your mount(8) command doesn't seem right: you're not saying which mountpoint to manipulate. (Don't forget that a device may be mounted in multiple locations.)
  • Your chmod(1) call also doesn't run with privileges and sets permissions way too open. Perhaps you don't care about security on your device, that's fine, but be certain that that is what you want.

I believe your mount command should look more like:

Runtime.getRuntime().exec("su -c \"mount -orw,remount /system\"");

And I believe your chmod command should look more like:

Runtime.getRuntime().exec("su -c \"chmod 777 /system/fonts\"");

Again, be certain you understand the consequences of allowing all users on the system privileges to write to any file that other users can execute.



回答2:

Runtime.getRuntime().exec

will return a Process, from the process class, you can

getInputStream  or getOutputStream or getErrorStream

from these method, you can get the command execute result, you can check it to ensure command execute right or wrong.