2017-04-10 138 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)); 
}