2016-03-07 165 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