Android访问内部存储 - 打开失败:EACCES(权限被拒绝)

时间:2017-01-20 11:28:25

标签: android

我被我的一个小项目困住了。 我想覆盖当前的锁屏壁纸,以便在每次锁定手机时更改其图像。我正在使用Android工作室使用API​​ 23。 我的手机有Android 6.0.1并且已经扎根了。 该代码可以将文件复制到非根目录。

我的问题是,在尝试将文件复制到data / data /时,我得到了

  

E / tag:/data/data/com.sec.android.wallpapercropper2/files/wallpaper.png:open failed:EACCES(Permission denied)

我想知道是否有一种简单的方法可以为我的应用程序提供超级用户权限。我在搜索时发现的唯一一件事是如何使用shell命令来完成它,但是如果可能的话我想用java代码来做。非常感谢!

public class MainActivity extends AppCompatActivity {

// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};

/**
 * Checks if the app has permission to write to device storage
 *
 * If the app does not has permission then the user will be prompted to grant permissions
 *
 * @param activity
 */
public static void verifyStoragePermissions(Activity activity) {
    // Check if we have write permission
    int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permission != PackageManager.PERMISSION_GRANTED) {
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                REQUEST_EXTERNAL_STORAGE
        );
    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    verifyStoragePermissions(this);
    copyFile("/storage/emulated/0/Download/", "wallpaper.png", "/data/data/com.sec.android.wallpapercropper2/files/");
}

private void copyFile(String inputPath, String inputFile, String outputPath) {
    InputStream in = null;
    OutputStream out = null;
    try {
        in = new FileInputStream(inputPath + inputFile);
        out = new FileOutputStream(outputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        in = null;

        // write the output file (You have now copied the file)
        out.flush();
        out.close();
        out = null;

    } catch (FileNotFoundException fnfe1) {
        Log.e("tag", fnfe1.getMessage());
    } catch (Exception e) {
        Log.e("tag", e.getMessage());
    }
}

1 个答案:

答案 0 :(得分:0)

我设法在rootTools

的帮助下解决了这个问题
CommandCapture command = new CommandCapture(0, "cp -f " + old_file + " " + new_file);
    try {
    RootTools.getShell(true).add(command);
    } catch(IOException io){}
    catch(TimeoutException ti){}
    catch(RootDeniedException rd){}