簡體   English   中英

ContentResolver openInputStream在后台下載文件

[英]ContentResolver openInputStream downloads the file in the background

因此,我正在嘗試下載一個大文件。 所以自然地,我的第一步是打開流

RNFetchBlob.RCTContext.getContentResolver().openInputStream(Uri.parse(fromUri));

我的問題是,這不是快速工作而只是打開流,而是實際上在后台下載內容。 我怎么知道? 好吧,這個命令會阻塞大約5分鍾,然后當我從流中讀取時,它是瞬時的。

我可以使此操作阻止在后台下載嗎? 我想通知用戶有關進度,而不僅僅是等待。

編輯:明確地說,我正在使用content:// URI作為資源

這是通過網絡讀取文件的錯誤方法,您需要使用特定於網絡的方法。

HttpURLConnection request = 
    (HttpURLConnection)(new URL(Uri.parse(fromUri)).openConnection());
// Connect to the server, expect a delay and draw a progress bar
request.connect();
// This will read HTTP headers with content length, expect another delay
// Must be called before request.getContentLength()
request.getInputStream();
// Get the size of your file, to draw your progress bar properly
long total = request.getContentLength();
// Now you can finally start reading the data
InputStream input = request.getInputStream();

對於長時間運行的HTTP下載,你可以使用DownloadManager ,例如像,並顯示下載進度這個的問題維克多拉爾特

  String urlDownload = <YOUR_URL>; DownloadManager.Request request = new DownloadManager.Request(Uri.parse(urlDownload)); request.setDescription("Testando"); request.setTitle("Download"); request.allowScanningByMediaScanner(); request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS,"teste.zip"); final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE); final long downloadId = manager.enqueue(request); final ProgressBar mProgressBar = (ProgressBar) findViewById(R.id.progressBar1); new Thread(new Runnable() { @Override public void run() { boolean downloading = true; while (downloading) { DownloadManager.Query q = new DownloadManager.Query(); q.setFilterById(downloadId); Cursor cursor = manager.query(q); cursor.moveToFirst(); int bytes_downloaded = cursor.getInt(cursor .getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)); int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)); if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) { downloading = false; } final int dl_progress = (int) ((bytes_downloaded * 100l) / bytes_total); runOnUiThread(new Runnable() { @Override public void run() { mProgressBar.setProgress((int) dl_progress); } }); Log.d(Constants.MAIN_VIEW_ACTIVITY, statusMessage(cursor)); cursor.close(); } } }).start(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM