2016-03-07 163 views
1

嗨,大家都在想知道是否有一段代码可以用来在下载完成后自动安装应用程序?如何在下载完成后自动安装apk安装

我的应用程序中有一个下载部分。我使用Google云端硬盘处理下载。但我遇到了一些设备的问题。所以我决定离开谷歌

我现在使用媒体火灾作为我的主机。我的应用使用直接下载。但它总是使用下载管理器下载。我希望它能做的更像Google Drive如何直接下载。这是它尽快下载completes.which我现在已经解决了与代码

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setDataAndType(Uri.fromFile(new 
File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), 
"application/vnd.android.package-archive"); 
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
startActivity(intent); 

这几行给我安装的选项有没有办法下载文件前检查下载文件夹。如果该文件已经在那里安装,如果没有得到网页下载。而是它说解析错误,然后去网页或同一文件的多个下载。

一如既往地提前致谢。

+1

你可以参考http://stackoverflow.com/questions/4967669/android-install-apk-programmatically –

+0

辉煌的感谢,将我需要编写,每下载或能实现它以写它只是一次,但是每次下载都会反复使用它。 –

+1

将它写入一个方法,该方法接受一个参数,比如apk的下载地址的url,或者它的固定路径,然后只是将apk的名称传递给该方法:)每次下载完成后用apk调用方法文件路径的名称:)我相信相同的代码应该适用于每个下载:) –

回答

0

下载完成后,您可以下载Uri,因此您不必指定要保存的文件名。如果你使用DownloadManager,下面是一个简单的例子。

final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); 
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse("http://remotehost/your.apk")); 
    final long id = downloadManager.enqueue(request); 
    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) { 
       Intent installIntent = new Intent(Intent.ACTION_VIEW); 
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { 
        installIntent.setDataAndType(downloadManager.getUriForDownloadedFile(id), 
          "application/vnd.android.package-archive"); 
       } else { 
        Cursor cursor = downloadManager.query(new DownloadManager.Query().setFilterById(id)); 
        try { 
         if (cursor != null && cursor.moveToFirst()) { 
          int status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS)); 
          String localUri = cursor.getString(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI)); 
          if (status == DownloadManager.STATUS_SUCCESSFUL) { 
           installIntent.setDataAndType(Uri.parse(localUri), "application/vnd.android.package-archive"); 
          } 
         } 
        } finally { 
         if (cursor != null) { 
          cursor.close(); 
         } 
        } 
       } 
       installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       context.sendBroadcast(installIntent); 
      } 
     } 
    }; 
    registerReceiver(broadcastReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)); 
+0

做这项工作,如果我有多个下载? –

+0

也在那里删除apk的请求。所以让我们说ive安装它,不要保存文件..但是,所以我有选择。 –

+0

@MarkMinecrafterHarrop您可以使用下载ID来跟踪多个下载。当然,你可以在安装完成后删除文件。你可以从'DownloadManager'获得下载文件的路径,然后删除它。 – alijandro