下载并打开文件到外部存储android

时间:2017-05-31 07:35:59

标签: android download android-external-storage

目前我正在尝试将文件从某个URL下载到我的设备的外部存储器或microd,然后在下载完成后打开它。我按照here

的回答

这里面是我的oncreate:

// execute this when the downloader must be fired
    final DownloadTask downloadTask = new DownloadTask(MainActivity.this);
    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, permission_external_memory);
        return;
    } else {
        downloadTask.execute("http://www.sample-videos.com/doc/Sample-doc-file-100kb.doc");
    }

这是我的下载程序asynctask代码:

private class DownloadTask extends AsyncTask<String, Integer, String> {

    private Context context;
    private PowerManager.WakeLock mWakeLock;

    public DownloadTask(Context context) {
        this.context = context;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // take CPU lock to prevent CPU from going off if the user
        // presses the power button during download
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                getClass().getName());
        mWakeLock.acquire();
        mProgressDialog.show();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        // if we get here, length is known, now set indeterminate to false
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setMax(100);
        mProgressDialog.setProgress(progress[0]);
    }

    @Override
    protected String doInBackground(String... sUrl) {
        InputStream input = null;
        OutputStream output = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(sUrl[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            // expect HTTP 200 OK, so we don't mistakenly save error report
            // instead of the file
            if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                return "Server returned HTTP " + connection.getResponseCode()
                        + " " + connection.getResponseMessage();
            }

            // this will be useful to display download percentage
            // might be -1: server did not report the length
            int fileLength = connection.getContentLength();

            // download the file
            input = connection.getInputStream();
            File mypath = new File(Environment.getExternalStorageDirectory(), "myfiletest.doc");
            output = new FileOutputStream(mypath);

            byte data[] = new byte[4096];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                // allow canceling with back button
                if (isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;
                // publishing the progress....
                if (fileLength > 0) // only if total length is known
                    publishProgress((int) (total * 100 / fileLength));
                output.write(data, 0, count);
            }
        } catch (Exception e) {
            return e.toString();
        } finally {
            try {
                if (output != null)
                    output.close();
                if (input != null)
                    input.close();
            } catch (IOException ignored) {
            }

            if (connection != null)
                connection.disconnect();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        mWakeLock.release();
        mProgressDialog.dismiss();
        if (result != null)
            Toast.makeText(context, "Download error: " + result, Toast.LENGTH_LONG).show();
        else {
            Toast.makeText(context, "File downloaded", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory(), "myfiletest.doc"), "text/*");
            context.startActivity(intent);
        }
    }

}

但是下载完成后,我无法打开文件,也无法通过文件管理器找到下载的文件。这是下载完成后尝试打开文件后显示的对话框: enter image description here

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

我已经尝试过您的代码了。它完美地工作而不是这一行:

intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory(), "myfiletest.doc"), "text/*");

所以我把它改成了:

 intent.setDataAndType(Uri.parse(Environment.getExternalStorageDirectory().getAbsolutePath()+"/myfiletest.doc"), "text/*");

并且从设置ans明确授予所有权限还包括所有必需的权限。下载后询问您要使用哪个应用程序打开下载的文件?选择适当的选项会打开一个文件。

所以你只缺少明确的权限。干杯!

编辑: 它保存到/storage/emulated/0/