DownloadCompleteReceiver.java 1.55 KB
package com.cnlive.goldenline.util;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;

/**
 * Created by gujun on 2017/4/20.
 *
 * 接受下载完成后的intent
 */

public class DownloadCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
            long receiveDownId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
            long sendDownId = SharedPreferencesHelper.getInstance(context).getLong("update_apk_download_id");
            if (sendDownId == receiveDownId) {
                Intent install = new Intent(Intent.ACTION_VIEW);
                DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(receiveDownId);
                Cursor cursor = manager.query(query);
                if (cursor.moveToFirst()) {
                    String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
                    install.setDataAndType(Uri.parse("file://" + filePath), "application/vnd.android.package-archive");
                    install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(install);
                }
            }
        }
    }
}