2017-05-31 84 views
0

當前我正在嘗試從某個URL下載文件到我的設備的外部存儲或microsd,然後在下載完成後打開它。我跟着從here下載並打開文件到外部存儲android

這裏的答案是我的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

我在這裏做了什麼錯誤?

+0

您可以提供的網址,你正在使用? – Kaushal28

+0

http://www.sample-videos.com/doc/Sample-doc-file-100kb.doc – user3576118

+0

您是否授予了書寫權限? – Kaushal28

回答

1

我試過了你的代碼。這是工作的完美,而不是這一行:

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

所以我把它改爲:

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

而且從設置ANS明確給出的所有權限也包括所有必要的權限。下載後請求使用哪個應用程序打開下載的文件?選擇適當的選項它會打開一個文件。

因此,您只缺少顯式權限。乾杯!

編輯: 它保存到/storage/emulated/0/

+0

對不起,先生我不太明白。是的,下載後,它詢問使用哪個應用程序來打開下載的文件。我也嘗試改變這條線。但是當我從設備的文件管理器或通過USB電纜通過我的電腦瀏覽時,我似乎無法找到下載的文件。我想我也檢查了所需的權限。 – user3576118

+0

在我的情況下,你的代碼在完成這些更改之後可以很好地工作。查看編輯。 – Kaushal28

+0

如果仍然找不到該文件,我會刪除答案。 – Kaushal28