/**
 * 文件名：CompleteReceiver.java
 * 描述：版本升级完毕处理
 * 包名：cn.com.kmlt.monstarBase.ver
 * 作者：WENJQ
 * 创建日期：2016年05月26日
 * 
 */
package com.mgq.base.ver;

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

import com.mgq.base.utils.logger.Logger;
import com.mgq.base.utils.toast.ToastUtil;


public class CompleteReceiver extends BroadcastReceiver {

	/** 
	* 方法名： 
	* 功能：
	*/
	public CompleteReceiver() {
		// TODO Auto-generated constructor stub
	}

	private DownloadManager downloadManager;

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

		String action = intent.getAction();
		if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
			ToastUtil.showToast(context, "下载完成");

			long id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0); //TODO 判断这个id与之前的id是否相等，如果相等说明是之前的那个要下载的文件  

			SharedPreferences sharedPreferences = context.getSharedPreferences(
					"update", context.MODE_PRIVATE);
			long mId = sharedPreferences.getLong("id", 0L);

			if (mId != id) {
				return;
			}

			Query query = new Query();
			query.setFilterById(id);
			downloadManager = (DownloadManager) context
					.getSystemService(Context.DOWNLOAD_SERVICE);
			Cursor cursor = downloadManager.query(query);


			if (cursor.moveToFirst()) {
				int columnIndex = cursor
						.getColumnIndex(DownloadManager.COLUMN_STATUS);
				if (DownloadManager.STATUS_SUCCESSFUL == cursor
						.getInt(columnIndex)) {
					String uriString = cursor.getString(cursor
							.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
					Logger.d("vketest", "uri: " + uriString);
					Intent mintent = new Intent(Intent.ACTION_VIEW);
					
					mintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

					mintent.setDataAndType(Uri.parse(uriString),
							"application/vnd.android.package-archive");

					context.startActivity(mintent);

				}
			}

			cursor.close();

		}
	}
}
