简体   繁体   English

仅在首次安装应用程序后创建的文件 - ANDROID

[英]File created only after first installation of the app - ANDROID

I have this code:我有这个代码:

private void requestPermissionAndExport() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(
                this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                1);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        try {
            export();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}


public void export() throws IOException {
    String csv_data = "testtest";
    File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);


    root = new File(root, "my_csv.csv");

    try {
        FileOutputStream fout = new FileOutputStream(root);
        fout.write(csv_data.getBytes());

        fout.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It works when I first install and launch the app.它在我第一次安装和启动应用程序时工作。 If the user deletes the csv file from the download folder and try to open the app again, and export csv again, nothing happens.如果用户从下载文件夹中删除csv文件并尝试再次打开应用程序,并再次导出csv ,则没有任何反应。 Also if I generate every time differents name for the file, only the first one (after installation of the app) is created.此外,如果我每次为文件生成不同的名称,则只会创建第一个(安装应用程序后)。 Why does this work only in the first instance?为什么这仅在第一种情况下有效?

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                       @NonNull int[] grantResults) {
    if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        try {
            export();
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Probably that's why.大概就是这个原因吧。 You call export() only inside onRequestPermissionsResult() and app asks for permissions only once, and remember it till you uninstall it.您只在onRequestPermissionsResult()内部调用export() ) 并且应用程序只请求一次权限,并记住它直到您卸载它。 Try it yourself: if you clear app data from app manager it will ask again, and then export file again too.自己尝试一下:如果您从应用管理器中清除应用数据,它会再次询问,然后再次导出文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM