0

currently I am trying to download files from a certain URL to the external storage or microsd of my device and then open it after the download is complete. I followed the answer from here

Here is inside my 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");
    }

And here is my downloader asynctask code:

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);
        }
    }

}

But after the download is completed, I can't open the file and I also can't find the downloaded file with file manager. This is the dialog shown after the download completed and trying to open the file: enter image description here

What did I do wrong here?

user3576118
  • 375
  • 1
  • 5
  • 24
  • can you provide which url you are using? – Kaushal28 May 31 '17 at 07:40
  • http://www.sample-videos.com/doc/Sample-doc-file-100kb.doc – user3576118 May 31 '17 at 07:42
  • have you granted writing permissions? – Kaushal28 May 31 '17 at 07:50
  • yes sir, I have put INTERNET, ACCESS_NETWORK_STATE, WRITE_EXTERNAL_STORAGE, and even READ_EXTERNAL_STORAGE – user3576118 May 31 '17 at 07:51
  • but if you are using Android 6.0 or higher, you need to grant permission explicitly. Have you granted it from settings? – Kaushal28 May 31 '17 at 07:53
  • yes, I had make sure to ask for permission before downloading the file and accept it. I also re-check it from settings->apps->myapp's permission and the storage permission has been checked on. – user3576118 May 31 '17 at 07:58
  • In onPostExecute you should add code to check if the file exists before trying that intent. Use File#exists(). Display a Toast() if not. – greenapps May 31 '17 at 08:09
  • Which app is it that complains "Can't open file"? – greenapps May 31 '17 at 08:10
  • what message does the onPostExecute-toast show? do you have internetpermissions neccessary to download? have you put a breakpoint into doInBackground and debugged it to see what happens? – k3b May 31 '17 at 08:12
  • 1
    `long total = 0;` How many bytes are downloaded all together? – greenapps May 31 '17 at 08:14
  • it is a 100kb flat sir, but actually this is just for testing, for the real implementaion I want to download apk files that could be few MBs to update the current apps since we dont want to upload it to google play but want to able to update it. – user3576118 May 31 '17 at 08:19
  • @greenapps it is microsoft word apps – user3576118 May 31 '17 at 08:45

1 Answers1

1

I've tried your code. It is working perfectly instead of this line:

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

So I changed it to:

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

And given all the permissions explicitly from settings ans also included all required permissions. After downloading it asks using which app you want to open the downloaded file? Selecting appropriate option it opens a file.

So the you are missing explicit permissions only. Cheers!

EDIT: It saved to /storage/emulated/0/

Kaushal28
  • 5,377
  • 5
  • 41
  • 72
  • I'm sorry sir I don't quite understand it. Yes, after downloading it asks using which app to open the downloaded file. I also try to change that line. But I just can't seem to find the downloaded file when browsing it from the device's file manager or via my computer with USB cable. I think I also have checked the permission required. – user3576118 May 31 '17 at 08:05
  • In my case you code is working perfectly after these changes. See the edits. – Kaushal28 May 31 '17 at 08:07
  • If still can't find the file, I'll delete the answer. – Kaushal28 May 31 '17 at 08:11
  • It's alright sir. I really appreciate your help. Its just because I'm new in implementing storage. Actually I have just found the file too, but not directly with my device's built in file manager or via my computer, but I find it with fx file manager – user3576118 May 31 '17 at 08:17