首页 > 解决方案 > Android:下载管理器请求缓存目录

问题描述

我需要使用本机下载管理器将敏感文件保存到缓存目录。用户无法发现的位置。我可以使用DownloadManager.Request(). 尽管使用setDestinationInExternalPublicDir()或任何其他方式设置目标,但不允许我保存到缓存目录。我在这里错过了什么吗?

标签: androidcaching

解决方案


您必须忘记下载管理器中的 Android 构建并创建自己的管理器。然后你可以下载到路径:getCacheDir().getAbsolutePath();

这是一个示例代码,可以在没有内置管理器的情况下自己下载文件

public String downloadFile(String fileURL, String fileName) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        Log.d(TAG, "Downloading...");
        try {
            int lastDotPosition = fileName.lastIndexOf('/');
            if( lastDotPosition > 0 ) {
                String folder = fileName.substring(0, lastDotPosition);
                File fDir = new File(folder);
                fDir.mkdirs();
            }

            //Log.i(TAG, "URL: " + fileURL);
            //Log.i(TAG, "File: " + fileName);
            URL u = new URL(fileURL);
            HttpURLConnection c = (HttpURLConnection) u.openConnection();
            c.setRequestMethod("GET");
            c.setReadTimeout(30000);
            c.connect();
            double fileSize  = (double) c.getContentLength();
            int counter = 0;
            while ( (fileSize == -1) && (counter <=30)){
                c.disconnect();
                u = new URL(fileURL);
                c = (HttpURLConnection) u.openConnection();
                c.setRequestMethod("GET");
                c.setReadTimeout(30000);
                c.connect();
                fileSize  = (double) c.getContentLength();
                counter++;
            }

            File fOutput = new File(fileName);
            if (fOutput.exists())
                fOutput.delete();

            BufferedOutputStream f = new BufferedOutputStream(new FileOutputStream(fOutput));
            InputStream in = c.getInputStream();
            byte[] buffer = new byte[8192];
            int len1 = 0;
            int downloadedData = 0;
            while ((len1 = in.read(buffer)) > 0) {
                downloadedData += len1;
                f.write(buffer, 0, len1);
            }
            Log.d(TAG, "Finished");
            f.close();

            return fileName;
        }
        catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
            return null;
        }
    }

推荐阅读