在android中设置文件读取权限

时间:2011-06-03 18:52:22

标签: java android file-permissions

我正在编写一个从网址下载* .apk的应用,然后尝试安装它。 在尝试让PackageManager安装时,我似乎遇到了Permission denied错误。 我想将文件的权限设置为可从java代码中读取。你是怎么做到的。

以下是我阅读文件的方式

InputStream input = new BufferedInputStream(url.openStream());
 OutputStream output = new FileOutputStream(PATH + fileName);

 byte data[] = new byte[1024];


 int count;

while((count = input.read(data)) != -1) {
                total += count;
                output.write(data, 0, count);
}

3 个答案:

答案 0 :(得分:2)

您无法使用PackageManager直接安装.apk文件。只有系统应用程序才能这样做。

但您可以要求系统使用标准安装工作流程安装应用程序。这是一个例子:

Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(new File(pathToApk));
intent.setDataAndType(uri, "application/vnd.android.package-archive");
startActivity(intent);

这一切都假设您实际上已成功下载.apk。但如果您在该步骤失败,则应检查WRITE_EXTERNAL_STORAGE权限。并检查您的SD卡是否未通过USB共享(如果是,您的应用程序将无权使用SD卡)。

答案 1 :(得分:1)

如果你想在Android 2.2及更高版本上更改文件权限,你可以使用它:

Runtime.getRuntime().exec("chmod 777 " + PATH + fileName);

在android 3中你也可以不使用本机代码解决方法:

new java.io.File(PATH + fileName).setReadable(true, false);

答案 2 :(得分:0)

我还没有尝试过这里要求的内容,但这会改变任何版本的android中的文件权限:

exec("chmod 0777 " + fileOfInterest.getAbsolutePath());  //whatever permissions you require

private void exec(String command) {
    Runtime runtime = Runtime.getRuntime();
    Process process;
    try {
        process = runtime.exec(command);
        try {
            String str;
            process.waitFor();
            BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            while ((str = stdError.readLine()) != null) {
                Log.e("Exec",str);
                mErrOcc = true;  //I use this elsewhere to determine if an error was encountered
            }
            process.getInputStream().close();
            process.getOutputStream().close();
            process.getErrorStream().close();
        } catch (InterruptedException e) {
            mErrOcc = true;
        }
    } catch (IOException e1) {
        mErrOcc = true;
    }
}

这就像Shmuel所暗示的那样,但是更完整和顺便说一下,他建议的是1.5和更高,而不是2.2和更高。

相关问题