如何使用FileProvider获取文件列表

时间:2014-07-25 14:48:23

标签: android android-contentprovider android-fileprovider

正在研究Android项目。 我需要提供ContentProvider来提供对某个目录的访问。 FileProvider对我来说是个很好的解决方案。 是否可以使用FileProvider检索目录中的文件列表?

1 个答案:

答案 0 :(得分:0)

用户ACTION_SEND_MULTIPLE发送多个URI

// Set up an Intent to send back to apps that request files
mResultIntent = new Intent("com.yourpacakgename.ACTION_SEND_MULTIPLE");
// Get the files/res subdirectory;
File mResDir = new File(getFilesDir(), "res");
// Get the files in the res subdirectory
File[] mResFiles = mResDir.listFiles();
// Uri list
ArrayList<Uri> uriArrayList = new ArrayList<Uri>();
// Set the Activity's result to null to begin with
setResult(Activity.RESULT_CANCELED, null);

Uri fileUri = null;
for (int i = 0; i < mResFiles.length; i++) {
    Log.i(TAG, mResFiles[i].getName());
    // Use the FileProvider to get a content URI
    try {
        fileUri = FileProvider.getUriForFile(this, this.getPackageName() + ".fileprovider", mResFiles[i]);
        // add current file uri to the list
        uriArrayList.add(fileUri);
    } catch (Exception e) {
        Log.e(TAG, "The selected file can't be shared: " + mResFiles[i].getPath());
        fileUri = null;
    }
}

if (uriArrayList.size() != 0) {
    // Put the UriList Intent
    mResultIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uriArrayList);
    mResultIntent.setType("application/*");
    // Grant temporary read permission to all apps
    mResultIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
    // if you want send this to a specific app
    //grantUriPermission("pacakgename of client app", fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
    // Set the result
    this.setResult(Activity.RESULT_OK, mResultIntent);
} else {
    // Set the result to failed
    mResultIntent.setDataAndType(null, "");
    this.setResult(RESULT_CANCELED, mResultIntent);
}
// Finish Activity and return Result to Caller
finish();