2017-04-10 127 views
0

我用DownloadManager庫下載了一個.apk文件,並且我有一個用於下載服務的BroadcastReceiver。這是我在onRecieve(代碼):Android DownloadManager類:getUriForDownloadedFile返回錯誤路徑

long id = intent.getExtras().getLong(DownloadManager.EXTRA_DOWNLOAD_ID); 
    DownloadManager dm = (DownloadManager)context.getSystemService(context.DOWNLOAD_SERVICE); 

    intent = new Intent(Intent.ACTION_VIEW); 
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    intent.setDataAndType(dm.getUriForDownloadedFile(id), "application/vnd.android.package-archive"); 
    context.startActivity(intent); 

這裏的問題是,當我打電話UriForDownloadedFile(ID)somtimes返回文件:///storage/emulated/0/Download/example.apk 和其它設備上返回 內容://下載/ all_downloads/183

,我不能用(內容://下載/ all_downloads/183)安裝APK路徑

回答

1

您知道DownloadManager下載的文件,因爲你是誰告訴它在哪裏下載它。所以,在Android 6.0和更舊的設備上擺脫getUriForDownloadedFile(id),並使用Uri.fromFile()作爲File,您告訴DownloadManager將文件下載到該文件中。

請注意,在Android 7.0+上,一旦您的targetSdkVersion達到24或更高,就必須使用contentUri。幸運的是,安裝程序知道如何處理Android 7.0及更高版本上的content方案。

+0

**注意! 'DownloadManager'並不總是下載到我確定的路徑!**什麼時候?當文件已存在於路徑中時。然後'DownloadManager'將它下載到另一個路徑中。 –

1
registerReceiver(
     new BroadcastReceiver() { 
      @Override public void onReceive(Context context, Intent intent) { 
       final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); 
       if (downloadId == 0) return; 

       final Cursor cursor = downloadManager.query(
        new DownloadManager.Query().setFilterById(downloadId)); 

       if (cursor.moveToFirst()) { 
        final String downloadedTo = cursor.getString(
         cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI)); 
        Log.d(TAG, "The file has been downloaded to: " + downloadedTo); 

        context.startActivity(new Intent(Intent.ACTION_VIEW) 
         .setDataAndType(Uri.parse(downloadedTo), 
           "application/pdf")); 
       } 
      } 
     }, 
     new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
} 
相關問題