Android 6 - 写入外部存储仅在第一次运行时失败

时间:2016-05-09 08:23:04

标签: android permissions writetofile

我知道一个问题几乎就像被问了好几次,但问题不同了。 我需要将数据写入外部存储器。我知道我需要在运行时在 Android 6 上请求权限。到目前为止,这一切都很好。只有一件事是奇怪的。授予的权限似乎仅在我第二次启动应用程序时

我的例子如下:

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_WRITE_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "Permission granted!");
                    write();
                } else {
                    Log.d(TAG, "No permission granted!");
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        boolean hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermission) {
            Log.d(TAG, "Has no permission! Ask!");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
        } else {
            Log.d(TAG, "Permission already given!");
            write();
        }
    }

    private void write(){
        Log.d(TAG, "Trying to write");
        // Get the directory for the user's public pictures directory.
        File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");
        if (! root.exists() && !root.mkdirs()) {
            Log.e(TAG, "Directory not created");
            return;
        }

        File testFile = new File(root, "TEST.tmp");
        FileWriter writer;
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("TEST TEST TEST");
            writer = new FileWriter(testFile, false);
            writer.append(sb.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "Write successful");
    }

按下按钮会调用正在检查权限的onClick()。如果被授予,则调用write()方法 - 如果没有,则要求许可。

因此,当第一次按下按钮时,会打开权限弹出窗口,单击“是”并假设它会写入我的测试文件。仍然,我收到以下错误消息,并且文件甚至没有创建目录:

D/LOG: Has no permission! Ask! 
D/LOG: Permission granted! 
D/LOG: Trying to write 
E/LOG: Directory not created

如果我再次点击(已获得许可),则仅显示

D/LOG: Permission already given!
D/LOG: Trying to write
E/LOG: Directory not created

实际上目录和文件都不存在。 所以我关闭应用并再次启动并按下按钮。 控制台显示:

D/LOG: Permission already given!
D/LOG: Trying to write
D/LOG: Write successful

Voila,现在目录和文件存在

那为什么它只在我第二次启动应用程序时才能运行?看来权限仅在应用启动时刷新。有什么想法吗?

----编辑----

与评论相关,我将exists()mkdirs()分开。

这个方法仍然如下:

private void write(){
        Log.d(TAG, "Trying to write");
        // Get the directory for the user's public pictures directory.
        File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");
        if (! root.exists()){
            if(!root.mkdirs()) {
                Log.e(TAG, "Directory not created");
                return;
            } else {
                Log.e(TAG, "Directory created");
            }
        }
        ...

尽管如此,应用程序第一次启动时,我还是没有创建Directory。下次启动应用程序时,会创建目录。所以这似乎不是问题。

另外,我添加了一个检查Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)是否存在的方法。即使在第一次开始时也是如此。什么是失败的是我的子文件夹的mkdirs()

3 个答案:

答案 0 :(得分:1)

发布于此处:https://stackoverflow.com/a/37135078/1565635 我相信我找到了解决方案 - 或者至少是解释。

事实证明,这似乎是一个更大的问题。更改写入外部存储的权限会更改此进程的Linux GID。 为了更改ID,必须重新启动进程。下次应用程序打开时,将设置新的groupID并授予权限。这导致得出的结论是这不是一个错误,但实际上是Linux和Android的一个更大的问题。

我通过第一次执行应用程序时请求权限来“解决”这个问题,并在获得权限时重新启动它:

PackageManager packageManager = getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(getPackageName());
        ComponentName componentName = intent.getComponent();
        Intent mainIntent = IntentCompat.makeRestartActivityTask(componentName);
        startActivity(mainIntent);
        System.exit(0);

我没有尝试的解决方案是创建一个在后台运行的服务(因此具有另一个进程ID)并授予它权限。这样只需要重新启动服务,而不是完整的应用程序。在不利方面,这可能会为流程之间的通信做更多的工作。如果我理解正确,内容提供商也可以工作,但也意味着更多的工作。

---编辑---

用户M66B(https://stackoverflow.com/a/32473449/1565635)找到了相关gid的列表。有关详细信息,请访问:https://android.googlesource.com/platform/frameworks/base/+/master/data/etc/platform.xml

答案 1 :(得分:0)

试试这段代码: -

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_WRITE_STORAGE: {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "Permission granted!");
                    write();
                } else {
                    Log.d(TAG, "No permission granted!");
                }
            }
        }
    }


    @Override
    public void onClick(View v) {
        File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");
        dircheck(root);
        filecheck(new File(root, "TEST.tmp"));
        boolean hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
        if (!hasPermission) {
            Log.d(TAG, "Has no permission! Ask!");
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
        } else {
            Log.d(TAG, "Permission already given!");
            write();
        }
    }

    private void dircheck(File file) {

            if (!file.exists()) {
                file.mkdirs();
            }

    }

    private void filecheck(File file){
        if(!file.exists()){
            file.createNewFile();
        }
    }
    private void write(){

        File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");

        File testFile = new File(root, "TEST.tmp");
        FileWriter writer;
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("TEST TEST TEST");
            writer = new FileWriter(testFile, false);
            writer.append(sb.toString());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "Write successful");
    }

答案 2 :(得分:0)

编辑回答: -

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST_WRITE_STORAGE: {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d(TAG, "Permission granted!");
                write();
            } else {
                Log.d(TAG, "No permission granted!");
            }
        }
    }
}


@Override
public void onClick(View v) {
    boolean hasPermission = (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
    if (!hasPermission) {
        Log.d(TAG, "Has no permission! Ask!");
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_WRITE_STORAGE);
    } else {
        Log.d(TAG, "Permission already given!");
        write();
    }
}

private void dircheck(File file) {
    if (!file.exists()) {
        file.mkdirs();
    }

}

private void filecheck(File file){
    if(!file.exists()){
        try {
            file.createNewFile();    
        }catch (Exception e){e.printStackTrace();}

    }
}
private void write(){
    File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");
    dircheck(root);
    filecheck(new File(root, "TEST.tmp"));

    File testFile = new File(root, "TEST.tmp");
    FileWriter writer;
    try {
        StringBuilder sb = new StringBuilder();
        sb.append("TEST TEST TEST");
        writer = new FileWriter(testFile, false);
        writer.append(sb.toString());
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    Log.d(TAG, "Write successful");
}