应用程序重新启动Android更新应用程序使用DownloadManager(避免多次下载)

时间:2016-06-26 20:08:32

标签: android broadcastreceiver android-download-manager sticky-broadcast

我试图通过使用下载管理器下载apk来更新我的应用程序。我已注册广播接收器以收听DownloadManager.ACTION_DOWNLOAD_COMPLETE中的MainActivity并以onReceive方式打开apk。 以下是代码:

public class MainActivity extends CordovaActivity {
private long downloadReference;
private DownloadManager downloadManager;
private IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    registerReceiver(downloadReceiver, intentFilter);

}

public void updateApp(String url) {
    //start downloading the file using the download manager
    downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    Uri Download_Uri = Uri.parse(url);
    DownloadManager.Request request = new DownloadManager.Request(Download_Uri);
    request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
    request.setAllowedOverRoaming(false);
    request.setDestinationInExternalFilesDir(MainActivity.this, Environment.DIRECTORY_DOWNLOADS, "myapk.apk");
    downloadReference = downloadManager.enqueue(request);
}


@Override
public void onDestroy() {
    //unregister your receivers
    this.unregisterReceiver(downloadReceiver);
    super.onDestroy();
}

private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        //check if the broadcast message is for our Enqueued download
        long referenceId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
        if (downloadReference == referenceId) {

            //start the installation of the latest version
                    Intent installIntent = new Intent(Intent.ACTION_VIEW);
                installIntent.setDataAndType(downloadManager.getUriForDownloadedFile(downloadReference),
                        "application/vnd.android.package-archive");
                installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(installIntent);

        }

    }

};

}
在点击UI中的按钮时调用

updateApp(url)。 现在单击按钮后,下载开始。让我们说在启动下载后应用程序已关闭(接收器未注册),当应用程序再次启动时,我遇到两种情况的问题。

  1. 我的应用重启后,上一次下载完成了 -
    downloadReference丢失,当我的接收方收到广播时,referenceId将不会与downloadReference相同,因此永远不会启动installIntent。所以 我必须再次单击“更新”按钮并启动下载。是 有办法避免这个问题吗?

  2. 之前的下载在我的应用重新启动之前完成 - 无法知道我之前的下载已完成 新开始的活动。我必须再次点击按钮并重新开始下载。有没有办法启用粘性 广播下载管理器?

1 个答案:

答案 0 :(得分:0)

为此,您必须按照您的喜好存储下载参考。然后,您可以使用DownloadManager.Query()查询DownloadManager,它将返回一个光标,其中包含您应用发布到DownloadManager的所有下载请求。然后,您可以匹配downloadReference ID,然后检查下载的状态。如果已完成,则可以从DownloadManager.COLUMN_LOCAL_FILENAME获取路径。

private void updateDownloadStatus(long downloadReference) {      
  DownloadManager.Query query = new DownloadManager.Query();

  // if you have stored the downloadReference. Else you have to loop through the cursor.
  query.setFilterById(downloadReference); 

  Cursor cursor = null;

  try {
    cursor = DOWNLOAD_MANAGER.query(query);
    if (cursor == null || !cursor.moveToFirst()) {
      // restart download
      return;
    }
    float bytesDownloaded =
        cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
    float bytesTotal =
        cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
    int columnIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
    int downloadStatus = cursor.getInt(columnIndex);
    int columnReason = cursor.getColumnIndex(DownloadManager.COLUMN_REASON);
    int failureStatus = cursor.getInt(columnReason);
    int filePathInt = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
    String filePath = cursor.getString(filePathInt);

    switch (downloadStatus) {
      case DownloadManager.STATUS_FAILED:
      case DownloadManager.ERROR_FILE_ERROR:
        // restart download
        break;

      case DownloadManager.STATUS_SUCCESSFUL:
        if (filePath != null) {
          //got the file 
        } else {
          //restart
        }
        break;

      case DownloadManager.STATUS_PENDING:
      case DownloadManager.STATUS_RUNNING:
      case DownloadManager.STATUS_PAUSED:
        /// wait till download finishes
        break;
    }
  } catch (Exception e) {
    Log.e("Error","message" + e.getMessage(), e);
  } finally {
    if (cursor != null) {
      cursor.close();
    }
  }
}