简体   繁体   English

Android - 获得在运行时写入辅助SD卡的权限

[英]Android - gain priviledges to write to secondary sd card at runtime

The WRITE_EXTERNAL_STORAGE permission must only grant write access to the primary external 
storage on a device. Apps must not be allowed to write to secondary external storage 
devices, except in their package-specific directories as allowed by synthesized 
permissions. Restricting writes in this way ensures the system can clean up files
when applications are uninstalled.

However i've seen that it is possible to gain write priviledges at runtime (Proof of concept: Total Commander) using the System File Explorer to select a folder for which write is allowed after the folder selection is complete. 但是我已经看到有可能在运行时获得写入权限(概念证明:Total Commander),使用系统文件资源管理器选择文件夹选择完成后允许写入的文件夹。 However I can't seem to find an example of how to implement this. 但是,我似乎无法找到如何实现这一点的示例。 Any help with that? 对此有何帮助? A screenshot of the folder selection that I'm reffering to is shown below. 我正在考虑的文件夹选择的屏幕截图如下所示。

在此输入图像描述

I guss i ll answer my own question for future visitors... 我想我将为未来的访客回答我自己的问题......

Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
intent.putExtra("android.content.extra.SHOW_ADVANCED", true);
startActivityForResult(intent, 1);


protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    boolean finish = true;
    boolean selectionWasCorrect = false;
    if(resultCode==RESULT_OK){ 
         //Take persistant permission. This way you can modify the selected folder ever after a device restart.
         Uri treeUri = data.getData();
         int takeFlags = data.getFlags()  & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
         getContentResolver().takePersistableUriPermission(treeUri, takeFlags); 
    }
}

All these are applicable only from KIT_KAT and above 所有这些仅适用于KIT_KAT及以上

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

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