未知 URL 内容://downloads/my_downloads [英] Unknown URL content://downloads/my_downloads

查看:40
本文介绍了未知 URL 内容://downloads/my_downloads的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下载管理器下载一些多媒体文件并对其进行分类.我也在使用 Crashlytics,这是我在不同设备和 Android 版本上经常遇到的错误:

I'm using Download Manger to download some multimedia files and categorize them. I'm also using Crashlytics and this is an error I frequently get on different devices and versions of Android:

java.lang.IllegalArgumentException: Unknown URL content://downloads/my_downloads
   at android.content.ContentResolver.insert(ContentResolver.java:862)
   at android.app.DownloadManager.enqueue(DownloadManager.java:1252)
   at com.myapp.LessonFragment$DownloadClickListener.onClick(SourceFile:570)
   at android.view.View.performClick(View.java:4262)
   at android.view.View$PerformClick.run(View.java:17351)
   at android.os.Handler.handleCallback(Handler.java:615)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:137)
   at android.app.ActivityThread.main(ActivityThread.java:4921)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:511)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
   at dalvik.system.NativeStart.main(NativeStart.java)

你可以在下面看到我的代码:

You can see my codes below:

private class DownloadClickListener implements View.OnClickListener {
    @Override
    public void onClick(View view) {
        // Check if download manager available before request
        if (!DownloadHelper.isDownloadManagerAvailable(getActivity())) {
            // Build custom alert dialog
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setMessage(R.string.download_manager_disabled);
            builder.setCancelable(false);
            builder.setPositiveButton(R.string.ok, (dialog, which) -> {
                dialog.dismiss();
            });
            // Create and display alert dialog
            AlertDialog dialog = builder.create();
            dialog.show();
            return;
        }

        // Display short toast on download clicked
        Toast.makeText(getActivity(), R.string.lesson_download_start, Toast.LENGTH_SHORT).show();

        // Get attach from view tag
        Attache attache = (Attache) view.getTag();

        // Get lesson using lesson id
        Lesson lesson = new Select().from(Lesson.class)
                .where(Condition.column("id").is(attache.getLessonId()))
                .querySingle();

        // Set file name from url and attache name
        Uri uri = Uri.parse(attache.getFile());
        String fileName = attache.getName() + '.'
                + MimeTypeMap.getFileExtensionFromUrl(attache.getFile());

        // Check if path directory not exist and create it
        String filePath = Environment.getExternalStorageDirectory() + "/myapp/" + lesson.getTitle() + "/";
        File path = new File(filePath);
        if (!path.exists() || !path.isDirectory()) {
            if (!path.mkdirs()) {
                Timber.e("Could not create path directory.");
            }
        }

        // Check if file exist and then delete it
        File file = new File(filePath, fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                Timber.v("%s just deleted.", fileName);
            }
        }

        // Create download manager request using url
        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setTitle(attache.getName());
        request.setDestinationInExternalPublicDir("/myapp/" + lesson.getTitle(), fileName);

        // Using DownloadManager for download attache file
        DownloadManager manager = (DownloadManager) getActivity().getSystemService(Context.DOWNLOAD_SERVICE);
        manager.enqueue(request);
    }
}

推荐答案

对于那些遇到错误 Unknown URI: content://downloads/public_downloads 的人.我设法通过在 this answer 中获得@Commonsware 给出的提示来解决此问题.我在 GitHub 上发现了 FileUtils 类.这里InputStream方法用于从Download目录中获取文件.

For those who are getting Error Unknown URI: content://downloads/public_downloads. I managed to solve this by getting a hint given by @Commonsware in this answer. I found out the class FileUtils on GitHub. Here InputStream methods are used to fetch file from Download directory.

 // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }

                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                };

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        }
                    } catch (Exception e) {}
                }

                // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }

                return destinationPath;
            }

这篇关于未知 URL 内容://downloads/my_downloads的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆