繁体   English   中英

如何在 Android Pie 中使用 Intent.ACTION_OPEN_DOCUMENT

[英]How to use Intent.ACTION_OPEN_DOCUMENT in Android Pie

我正在使用 android 饼图中的 Retrofit 更改个人资料照片 function。

于是我就成功的把用相机拍的照片上传到了服务器上。 但我不知道如何将从图库中选择的照片传输到我的服务器。 (我可以使用 Java Kotlin 中的任何类型的代码。)

我稍后会上传视频。

我在谷歌上搜索了很多,但很难得到我想要的信息。

在谷歌文档中做得很好,但我不知道该怎么做。 https://developer.android.com/guide/topics/providers/document-provider

谷歌文档显示了使用 bitmap 或 inputstream 或其他东西的示例。

我是否需要 bitmap 或输入流才能使用 Retrofit 上传照片?

我实际上需要一个有效的 uri。

public void performFileSearch() {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setType("image/*");
        startActivityForResult(intent, PICTURES_DIR_ACCESS_REQUEST_CODE);
}


@Override
public void onActivityResult(int requestCode, int resultCode,Intent resultData) {
    if (requestCode == READ_REQUEST_CODE && resultCode ==Activity.RESULT_OK) {
        Uri uri = null;
        if (resultData != null) {
            uri = resultData.getData();
            Log.i(TAG, "Uri: " + uri.toString());
            showImage(uri);
        }
    }
}


public void Edit_Profile (String Image_Uri) {
    File file = new File(Image_Uri);
    RequestBody requestBody = RequestBody.create(file, MediaType.parse("image/*"));

    MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", Num+ID+".jpg", requestBody);
}

实际上,onActivityResult 返回以下类型的 uri。

content://com.android.providers.media.documents/document/image%3A191474

因此,当我尝试使用该 uri 将其发送到我的服务器时,我收到 FileNotFoundException 错误。

这是 Android-Q 中引入的隐私限制。 当应用程序以 API 29 为目标并且从getExternalStorageDirectory方法返回的路径不再可供应用程序直接访问时,不推荐直接访问共享/外部存储设备。 使用特定于应用程序的目录来写入和读取文件。

默认情况下,针对 Android 10 及更高版本的应用程序被授予对外部存储或范围存储的范围访问权限 此类应用程序可以在外部存储设备中查看以下类型的文件,而无需请求任何与存储相关的用户权限:

应用程序特定目录中的文件,使用 getExternalFilesDir() 访问。 应用程序从媒体商店创建的照片、视频和音频剪辑。

Go 通过文档使用存储访问框架打开文件

谈到上下文,您可以做的一件事是,正如 CommonsWare 建议的那样使用InputStreamRequestBody 否则,将所选文件复制到您的应用程序沙箱文件夹 IE,即应用程序特定目录,然后在没有任何权限的情况下从那里访问该文件。 只需查看以下适用于 Android-Q 及更高版本的实现即可。

执行文件搜索

private void performFileSearch(String messageTitle) {
        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
        intent.setType("application/*");
        String[] mimeTypes = new String[]{"application/x-binary,application/octet-stream"};
        if (mimeTypes.length > 0) {
            intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        }

        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(Intent.createChooser(intent, messageTitle), OPEN_DIRECTORY_REQUEST_CODE);
        } else {
            Log.d("Unable to resolve Intent.ACTION_OPEN_DOCUMENT {}");
        }
    }

onActivityResult 返回

@Override
public void onActivityResult(int requestCode, int resultCode, final Intent resultData) {
        // The ACTION_OPEN_DOCUMENT intent was sent with the request code OPEN_DIRECTORY_REQUEST_CODE.
        // If the request code seen here doesn't match, it's the response to some other intent,
        // and the below code shouldn't run at all.
        if (requestCode == OPEN_DIRECTORY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                // The document selected by the user won't be returned in the intent.
                // Instead, a URI to that document will be contained in the return intent
                // provided to this method as a parameter.  Pull that uri using "resultData.getData()"
                if (resultData != null && resultData.getData() != null) {
                    new CopyFileToAppDirTask().execute(resultData.getData());
                } else {
                    Log.d("File uri not found {}");
                }
            } else {
                Log.d("User cancelled file browsing {}");
            }
        }
    }

文件写入应用程序特定路径

public static final String FILE_BROWSER_CACHE_DIR = "CertCache";

@SuppressLint("StaticFieldLeak")
private class CopyFileToAppDirTask extends AsyncTask<Uri, Void, String> {
    private ProgressDialog mProgressDialog;

    private CopyFileToAppDirTask() {
        mProgressDialog = new ProgressDialog(YourActivity.this);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mProgressDialog.setMessage("Please Wait..");
        mProgressDialog.show();
    }

    protected String doInBackground(Uri... uris) {
        try {
            return writeFileContent(uris[0]);
        } catch (IOException e) {
            Log.d("Failed to copy file {}" + e.getMessage());
            return null;
        }
    }

    protected void onPostExecute(String cachedFilePath) {
        mProgressDialog.dismiss();
          if (cachedFilePath != null) {
                Log.d("Cached file path {}" + cachedFilePath);
            } else {
               Log.d("Writing failed {}");
         }

    }
}

private String writeFileContent(final Uri uri) throws IOException {
    InputStream selectedFileInputStream =
            getContentResolver().openInputStream(uri);
    if (selectedFileInputStream != null) {
        final File certCacheDir = new File(getExternalFilesDir(null), FILE_BROWSER_CACHE_DIR);
        boolean isCertCacheDirExists = certCacheDir.exists();
        if (!isCertCacheDirExists) {
            isCertCacheDirExists = certCacheDir.mkdirs();
        }
        if (isCertCacheDirExists) {
            String filePath = certCacheDir.getAbsolutePath() + "/" + getFileDisplayName(uri);
            OutputStream selectedFileOutPutStream = new FileOutputStream(filePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = selectedFileInputStream.read(buffer)) > 0) {
                selectedFileOutPutStream.write(buffer, 0, length);
            }
            selectedFileOutPutStream.flush();
            selectedFileOutPutStream.close();
            return filePath;
        }
        selectedFileInputStream.close();
    }
    return null;
}

  // Returns file display name.
    @Nullable
    private String getFileDisplayName(final Uri uri) {
        String displayName = null;
        try (Cursor cursor = getContentResolver()
                .query(uri, null, null, null, null, null)) {
            if (cursor != null && cursor.moveToFirst()) {
                displayName = cursor.getString(
                        cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
                Log.i("Display Name {}" + displayName);

            }
        }

        return displayName;
    }

这是一个可能更通用的解决方案,它允许 AsyncTask class 是独立的,而不是嵌入到活动中。 它还会在任务完成时返回对您的活动的响应,并使用 ProgressBar 而不是已弃用的 ProgressDialog。

异步任务:

public class FileLoader extends AsyncTask<Uri, Void, String>
{
    private WeakReference<Context> contextRef;
    public AsyncResponse delegate = null;

    public interface AsyncResponse {
    void fileLoadFinish(String result);
    }
    FileLoader(Context ctx , AsyncResponse delegate) {
        contextRef = new WeakReference<>(ctx);
        this.delegate =  delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    protected String doInBackground(Uri... uris) {
        Context context = contextRef.get();
         ContentResolver contentResolver = context.getContentResolver();

        Uri uri = uris[0];
        try {
            String mimeType = contentResolver.getType(uri);
            Cursor returnCursor =
                contentResolver.query(uri, null, null, null, null);
            int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            returnCursor.moveToFirst();
            String fileName = returnCursor.getString(nameIndex);
            InputStream inputStream =  contentResolver.openInputStream(uri);

            File downloadDir = 
              context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            File f = new File(downloadDir +  "/" + fileName);

            FileOutputStream out = new FileOutputStream(f);
            IOUtils.copyStream(inputStream,out);
            returnCursor.close();
            return  f.getPath();
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String result) {
        delegate.fileLoadFinish(result);
        super.onPostExecute(result);
    }
}

在您的活动中:

private static final int DIR_ACCESS_REQUEST_CODE = 13;
public void performFileSearch() {
    Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/*");
    String[] mimeTypes = new String[]{"application/gpx+xml","application/vnd.google-earth.kmz"};
    intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(Intent.createChooser(intent, "Choose KMZ or GPX file"), DIR_ACCESS_REQUEST_CODE);
    } else {
        Log.d("****File","Unable to resolve Intent.ACTION_OPEN_DOCUMENT");
    }
}


@Override
public void onActivityResult(int requestCode, int resultCode,Intent resultData)
{
    super.onActivityResult(requestCode, resultCode, resultData);
    if (requestCode == DIR_ACCESS_REQUEST_CODE && resultCode == Activity.RESULT_OK)
    {
        if (resultData != null)
        {
            Uri uri = resultData.getData();

            mProgressBar.setVisibility(View.VISIBLE);
            new FileLoader(this,
                new FileLoader.AsyncResponse(){
                    @Override
                    public void fileLoadFinish(String result){
                        processFile(new File(result));
                        mProgressBar.setVisibility(View.GONE);
                    }
                }).execute(uri);
         }
    }
}

我的示例尝试查找.kmz 文件或.gpx 文件。 进度条(如果需要,用于长时间运行的文件操作)需要在 OnCreate() 中初始化(并隐藏):

mProgressBar = findViewById(R.id.progressbar);
mProgressBar.setVisibility(View.GONE);

我的“processFile()”方法在主要活动中操作 map 需要一段时间,所以我一直等到它完成后才隐藏 ProgressBar。

我仍然惊讶于执行如此简单的操作需要如此多的代码:复制文件并使其可供使用!

暂无
暂无

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

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