在android中添加图像文件的完整权限。

时间:2012-03-27 06:11:54

标签: android file

我使用以下代码为android中的图像文件添加完整权限。 此代码不是每次都有效。想象一下有三个图像文件,A.png,B.png和C.png。在某些情况下,所有文件都将获得完全权限。在某些情况下,A.png将获得并在某些条件下获得或A和B将获得完全许可。我找不到原因。请帮我找出原因。

String iconFile = themePrefs.getString(info.activityInfo.name, ""); // Icon file = "/data/data/com.android.settings/MyApp/A.png";
System.out.println("FileExecute " + ico.canExecute());     //always false
System.out.println("FileRead " + ico.canRead());           //always false
System.out.println("FileWrite " + ico.canWrite());         //always false
System.out.println("FileExists " + ico.exists());          //always true
System.out.println("FileisFile " + ico.isFile());          //always true
System.out.println("FileisDirectory " + ico.isDirectory());//always false

Drawable d = null;
FileInputStream fis; // in stream
try {
    File ico = new File(iconFile); //creating a file with the path (because only this is working with absolute path)
    try {
         Runtime.getRuntime().exec("chmod 777 " + iconFile);   
    } catch (IOException e1) {
     // TODO Auto-generated catch block
                        e1.printStackTrace();
    }
    System.out.println("FileExecute " + ico.canExecute());      // Sometimes getting true, Sometimes false 
    System.out.println("FileRead " + ico.canRead());            // Sometimes getting true, Sometimes false
    System.out.println("FileWrite " + ico.canWrite());          // Sometimes getting true, Sometimes false
    System.out.println("FileExists " + ico.exists());           // always true
    System.out.println("FileisFile " + ico.isFile());           // always true
    System.out.println("FileisDirectory " + ico.isDirectory()); // always false
}
catch (OutOfMemoryError e) {
    e.printStackTrace();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} catch(NullPointerException ne) {
    ne.printStackTrace();
}

1 个答案:

答案 0 :(得分:6)

如果您没有从正在运行的上下文中读取,写入权限,则无法从相同的上下文执行chmod。更改为超级用户(su。为此设备必须已植根),然后您可以更改模式。这是代码。有用。我测试了它。感谢

void gainRoot()
{
    Process chperm;
    try {
        chperm=Runtime.getRuntime().exec("su");
          DataOutputStream os = 
              new DataOutputStream(chperm.getOutputStream());
            os.writeBytes("chmod 777 /data/data/com.android.settings/MyApp/A.png\n");
            os.flush();
            os.writeBytes("chmod 777 /data/data/com.android.settings/MyApp/B.png\n");
            os.flush();
            os.writeBytes("chmod 777 /data/data/com.android.settings/MyApp/C.png\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();
    }
}

准确使用代码并检查您的设备是否已植根。它应该工作。从oncreate()调用gainRoot()。如果您有任何困难,请告诉我。感谢