package com.tagmae.tsgame_erwang;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.game.webgame.view.SpUtil;
import com.game.webgame.view.dialogexit;
import com.game.webgame.view.dialogexit.onexitlistener;
import com.game.webgame.view.pmutil;
import com.google.gson.Gson;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.CsvFormatStrategy;
import com.orhanobut.logger.DiskLogAdapter;
import com.orhanobut.logger.Logger;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;


import com.jx.jyhd.R;
import com.jx.jyhd.simcpux.Constants;
import com.jx.jyhd.simcpux.Util;
import com.jx.jyhd.simcpux.Wxistrue;
import com.jx.jyhd.wxapi.WXEntryActivity;
import com.tsgame.tsgame_niuniu.Bean.Gameversiontxt;
import com.tsgame.tsgame_niuniu.Bean.agentlistTxt;
import com.tsgame.tsgame_niuniu.Bean.channellistTxt;
import com.tsgame.tsgame_niuniu.Bean.filelistBean;
import com.tsgame.tsgame_niuniu.Bean.gamelistTxt;
import com.tsgame.tsgame_niuniu.Bean.marketlistTxt;
import com.tsgame.tsgame_niuniu.Bean.userbean;
import com.tsgame.tsgame_niuniu.Bean.versionagentlist;
import com.tsgame.tsgame_niuniu.Bean.versionbean;

import com.tsgame.tsgame_niuniu.Bean1.Agentlist;
import com.tsgame.tsgame_niuniu.Bean1.ConfigData;
import com.tsgame.tsgame_niuniu.Bean1.Gamelist;
import com.tsgame.tsgame_niuniu.Bean1.JsonRootBean;
import com.tsgame.tsgame_niuniu.Bean1.gameversionUtil;
import com.tsgame.tsgame_niuniu.system.Gamesettingurl;
import com.tsgame.tsgame_niuniu.system.Myapplication;
import com.tsgame.tsgame_niuniu.util.Settingutil;
import com.tsgame.tsgame_niuniu.util.ZipUtils;
import com.tsgame.tsgame_niuniu.util.apputil;
import com.tsgame.tsgame_niuniu.util.initwebviewutil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.MobclickAgent.EScenarioType;
import com.umeng.analytics.game.UMGameAgent;

// Apache HttpClient已移除，改用OkHttp
// import org.apache.http.HttpEntity;
// import org.apache.http.HttpResponse;
// import org.apache.http.client.ClientProtocolException;
// import org.apache.http.client.HttpClient;
// import org.apache.http.client.methods.HttpGet;
// import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipException;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@SuppressLint("NewApi")
public class weclomeactivity1 extends AppCompatActivity{

	ProgressBar progressBar;
	String m_appNameStr = "tsgame_niuniu.apk"; // 下载到本地要给这个APP命的名字
	// 添加APK文件路径变量，用于安装
	private String apkFilePathForInstall = "";
	List<filelistBean> testBean;
	ProgressDialog m_progressDlg1;

	private SharedPreferences sp;


	@SuppressLint("InlinedApi")
	String[] permissons = new String[] { Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE };
	private static final String PACKAGE_URL_SCHEME = "package:"; // 方案

	private String projectpath;// 解压路径
	TextView inittext;
	TextView textView1;
	private static final int disend = 1;
	private static WakeLock m_wklk;
	Handler m_mainHandler;

	public void setshowmessage(String Showmessage) {
		System.out.println("----" + Showmessage);
		if (!pmutil.isnullorEmpty(Showmessage)) {
			apputil.Showmessage = Showmessage;

		}
	}

	int i=0;

	@SuppressLint("HandlerLeak")
	Handler hanlerq1 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Gson fson = new Gson();
			String s;
			switch (msg.what){
				case 1:
					s=msg.getData().getString("msg");
					//保存获取配置文件数据
					SpUtil.setStringSharedPerference(Shared,"gameconfig",s);
					long time=System.currentTimeMillis();
					SpUtil.setLongSharedPerference(Shared,"gameconfigtime",time);
					mJsonRootBean = fson.fromJson(s, JsonRootBean.class);
					if(mJsonRootBean.getGamelist()!=null){
						//处理2。0配置
						chulisuoyin();
					}else{
						// 兼容1.0配置
						gameversiontxt = fson.fromJson(s, Gameversiontxt.class);
						chuliversion_1();
					}
					break;
				case 2:
					s=msg.getData().getString("msg");
					SpUtil.setStringSharedPerference(Shared,"magentlist",s);
					Logger.t("hanlerq1").v(s);
					magentlist=fson.fromJson(s, Agentlist.class);
					chulipeizhiAgent();
					break;
				case 3:
					s=msg.getData().getString("msg");
					SpUtil.setStringSharedPerference(Shared,"mgamelist",s);
					Logger.t("hanlerq1").v(s);
					mgamelist=fson.fromJson(s, Gamelist.class);
					chulipeizhiGame();
					break;
				case 4:
					i++;//
					if(i==2){//两个配置文件读取完成
						if(!pmutil.isnullorEmpty(apputil.Showmessage)){
							showMissingsettingDialog(apputil.Showmessage);
						}else{
							if(agentversionutil!=null&&gameversionutil!=null){
								chulipeizhi();
							}
						}
					}
					break;
			}
			super.handleMessage(msg);

		}
	};
	public void chuliversion_1(){
		apputil.Showmessage = "";

		setshowmessage(gameversiontxt.getShowmessage());

		List<agentlistTxt> versionagentinfo = gameversiontxt.getAgentlist();

		String urlpath = SpUtil.getStringSharedPerference(sp, "urlpath");
		String purl = urlpath + File.separator + Settingutil.initfile;

		System.out.println("purl=" + purl);

		versionbean versd = pullxml1(purl);

		String gameid = getAllFilename("gameid");
		if(!pmutil.isnullorEmpty(gameid)){
			versd.setGameid(gameid);
		}

		System.out.println(versd.toString());
		String channel = getAllFilename("channel");
		String marketname = getAllFilename("market");
		System.out.println(getAllFilename("market"));
		String agentid = getAllFilename("agent");
		System.out.println("agentid=" + agentid);
		System.out.println("channel===" + channel);
		int xmlgamecode = Integer.parseInt(versd.getVersion());

		if (!pmutil.isnullorEmpty(channel)) {
			versd.setChannelid(channel);
		}

		boolean isgameutil = false;

		System.out.println("进入配置文件");

		for (int k = 0; k < versionagentinfo.size(); k++) {
			agentlistTxt agenttext = versionagentinfo.get(k);
			System.out.println(agenttext.toString());
			System.out.println(""+agentid);
			System.out.println("agenttext.getAgentid()="+agenttext.getAgentid());

			if (agenttext.getAgentid().equals(agentid)) {
				System.out.println("代理id匹配"+agentid);
				System.out.println("代理id匹配"+agenttext.getAgentid());
				setshowmessage(versionagentinfo.get(k).getShowmessage());

				List<gamelistTxt> info = gameversiontxt.getAgentlist()
						.get(k).getGamelist();

				for (int i = 0; i < info.size(); i++) {
					gamelistTxt gamelistfo = info.get(i);

					if (gamelistfo.getGameid().equals(versd.getGameid())) {
						System.out.println("游戏id匹配");
						setshowmessage(gamelistfo.getShowmessage());

						String newgame_zip = "";
						String newgame_version = "";
						if (!pmutil.isnullorEmpty(gamelistfo.getGame_zip())) {
							newgame_zip = gamelistfo.getGame_zip();

						}

						if (!pmutil.isnullorEmpty(gamelistfo
								.getGame_version())
								&& !gamelistfo.getGame_version()
								.equals("0")) {
							newgame_version = gamelistfo.getGame_version();
						}

						List<channellistTxt> info1 = gamelistfo
								.getChannellist();
						for (int j = 0; j < info1.size(); j++) {
							channellistTxt info2 = info1.get(j);

							String Channelid = info2.getChannelid();
							System.out.println("------" + Channelid);
							if (Channelid.equals(versd.getChannelid())) {

								setshowmessage(info2.getShowmessage());

								System.out.println("渠道id匹配");

								if (!pmutil.isnullorEmpty(info2
										.getGame_zip())) {
									newgame_zip = info2.getGame_zip();

								}

								if (!pmutil.isnullorEmpty(info2
										.getGame_version())
										&& !info2.getGame_version().equals(
										"0")) {
									newgame_version = info2
											.getGame_version();
								}

								List<marketlistTxt> marketlist = info2
										.getMarketlist();

								for (int f = 0; f < marketlist.size(); f++) {
									marketlistTxt marketinfo = marketlist
											.get(f);
									if (marketinfo.getMarketid().equals(
											marketname)) {
										System.out.println("市场id 匹配");

										setshowmessage(marketinfo
												.getShowmessage());

										if (!pmutil
												.isnullorEmpty(apputil.Showmessage)) {

											showMissingsettingDialog(apputil.Showmessage);

										} else {
											isgameutil = true;
											String downloadurl = marketinfo
													.getApp_download();

											int versioncode = Integer
													.parseInt(marketinfo
															.getApp_version());// apk

											int gameversioncode = 0;

											try {
												if (!pmutil
														.isnullorEmpty(newgame_version)) {
													gameversioncode = Integer
															.parseInt(newgame_version);

												}

											} catch (Exception e) {

											}

											// 版本
											if (!pmutil
													.isnullorEmpty(marketinfo
															.getGame_version())
													&& !marketinfo
													.getGame_version()
													.equals("0")) {
												gameversioncode = Integer
														.parseInt(marketinfo
																.getGame_version());// 游戏
											}

											int AppVersioncode = 1;

											String apkversion = getAllFilename("appversion");
											//
											if (pmutil
													.isnullorEmpty(apkversion)) {

											} else {
												AppVersioncode = Integer
														.parseInt(apkversion);
											}

											// 版本
											if (AppVersioncode > versioncode) {
												apputil.code = 1;
											} else {
												apputil.code = 0;
											}

											System.out
													.println("AppVersioncode"
															+ AppVersioncode);

											System.out
													.println("versioncode"
															+ versioncode);

											boolean isupdate = false;

											if (versioncode > AppVersioncode) {
												progressBar.setVisibility(View.VISIBLE);
												inittext.setText("下载apk安装包...");
												isupdate = true;
												doNewVersionUpdate(downloadurl+"?a="+System.currentTimeMillis());

											}

											System.out
													.println("gameversioncode"
															+ gameversioncode
															+ "xmlgamecode"
															+ xmlgamecode);
											if (!isupdate) {
												if (gameversioncode > xmlgamecode) {
													inittext.setText("正在升级版本...");
													progressBar.setVisibility(View.VISIBLE);
													if (!pmutil
															.isnullorEmpty(marketinfo
																	.getGame_zip())) {
														System.out
																.println("---"
																		+ marketinfo
																		.getGame_zip());

														updatezip(marketinfo
																.getGame_zip()+"?a="+System.currentTimeMillis());
													} else {
														if (!pmutil
																.isnullorEmpty(newgame_zip)) {
															updatezip(newgame_zip+"?a="+System.currentTimeMillis());
														} else {
															showMissingsettingDialog();
														}

													}

												} else {
													if (!isupdate) {
														handlerend1();
													}
												}
											}
										}

									}
								}

								//
							}

						}
					}

				}

			} else {

			}

		}
		if (!isgameutil) {
			if (!pmutil.isnullorEmpty(apputil.Showmessage)) {
				showMissingsettingDialog(apputil.Showmessage);
			} else {
				showMissingsettingDialog();
			}

		}

	}

	ConfigData mconfigData;

	public ConfigData getConfigData(){
		if(mconfigData==null){
			mconfigData=new ConfigData();
			mconfigData.setAgentid(getAllFilename("agent"));

			String urlpath = SpUtil.getStringSharedPerference(sp, "urlpath");
			String purl = urlpath + File.separator + Settingutil.initfile;

			versionbean versd = pullxml1(purl);
			String gameid=getAllFilename("gameid");
			if(!pmutil.isnullorEmpty(gameid)){
				versd.setGameid(gameid);
			}

			mconfigData.setGameid(versd.getGameid());
			mconfigData.setChannelid(getAllFilename("channel"));
			String marketname = getAllFilename("market");
			mconfigData.setMarketid(marketname);
		}
		return mconfigData;


	}
	gameversionUtil agentversionutil;
	gameversionUtil gameversionutil;

	GameupdateUtil gameupdateUtil;

	public void chulipeizhiAgent(){
		ConfigData mconfigData=getConfigData();
		if(gameupdateUtil==null){
			gameupdateUtil=new GameupdateUtil();
		}

		agentversionutil=gameupdateUtil.agentUtil(mconfigData,magentlist,null);
		hanlerq1.sendEmptyMessage(4);
	}

	public void chulipeizhiGame(){
		if(gameupdateUtil==null){
			gameupdateUtil=new GameupdateUtil();
		}
		ConfigData mconfigData=getConfigData();
		gameversionutil=gameupdateUtil.agentUtil(mconfigData,null,mgamelist);
		hanlerq1.sendEmptyMessage(4);
	}

	public void chulisuoyin(){
		apputil.Showmessage = "";
		String agentid = getAllFilename("agent");

		String urlpath = SpUtil.getStringSharedPerference(sp, "urlpath");
		String purl = urlpath + File.separator + Settingutil.initfile;
		versionbean versd = pullxml1(purl);
		String gameid1 = getAllFilename("gameid");
		if(!pmutil.isnullorEmpty(gameid1)){
			versd.setGameid(gameid1);
		}
		String gameid =versd.getGameid();
		setshowmessage(mJsonRootBean.getShowmessage());
		if(!pmutil.isnullorEmpty(gameid)&&!pmutil.isnullorEmpty(agentid)){
			for(int i=0;i<mJsonRootBean.getAgentlist().size();i++){

				Agentlist agentlist=mJsonRootBean.getAgentlist().get(i);
				if(agentlist.getAgentid().equals(agentid)){
					Logger.v("agentlist.getAgentid()="+agentlist.getAgentid()+"--"+agentid);
					setshowmessage(agentlist.getShowmessage());
					if(!pmutil.isnullorEmpty(agentlist.getUrl())){
						//获取代理配置
						Logger.t("welcome").v("agentlist.getUrl()="+agentlist.getUrl());
						updateapk2(agentlist.getUrl(),2);
						//break;
					}else{
						Logger.t("welcome").d("agent配置文件地址为空");

					}
					break;
				}
			}

			for(int i=0;i<mJsonRootBean.getGamelist().size();i++){

				Gamelist gamelist=mJsonRootBean.getGamelist().get(i);
				if(gamelist.getGameid().equals(gameid)){
					Logger.v("gamelist.getGameid()="+gamelist.getGameid()+"--"+gameid);
					setshowmessage(gamelist.getShowmessage());

					if(!pmutil.isnullorEmpty(gamelist.getUrl())){
						//获取代理配置
						Logger.t("welcome").v("gamelist.getUrl()="+gamelist.getUrl());
						updateapk2(gamelist.getUrl(),3);
					}else{
						Logger.t("welcome").d("game配置文件地址为空");
					}

					break;

				}

			}

		}


	}
	public void chulipeizhi(){
		String appdownloadurl="";
		int appdownloadversion=0;
		String gamedownloadurl="";
		int gamedownloadversion=0;


		//处理自app升级
		if(!pmutil.isnullorEmpty(gameversionutil.getApp_download())&&!pmutil.isnullorEmpty(agentversionutil.getApp_download())){
			//两个配置文件都配置了app升级取配置版本最高都
			try{
				appdownloadversion=Integer.parseInt(agentversionutil.getApp_version());
				appdownloadurl=agentversionutil.getApp_download();
				if(Integer.parseInt(gameversionutil.getApp_version())>appdownloadversion){
					appdownloadversion=Integer.parseInt(gameversionutil.getApp_version());
					appdownloadurl=gameversionutil.getApp_download();

				};
			}catch (Exception e){

				Logger.e("APP配置version格式版本问题",e);
			}



		}else{
			try{
				if(!pmutil.isnullorEmpty(gameversionutil.getApp_download())){

					appdownloadversion=Integer.parseInt(gameversionutil.getApp_version());
					appdownloadurl=gameversionutil.getApp_download();
				}
			}catch (Exception e){
				Logger.e("gameversionutil配置APP version格式版本问题",e);
			}
			try{

				if(!pmutil.isnullorEmpty(agentversionutil.getApp_download())){
					appdownloadversion=Integer.parseInt(agentversionutil.getApp_version());
					appdownloadurl=agentversionutil.getApp_download();
				}
			}catch (Exception e){
				Logger.e("agentversionutil配置APP version格式版本问题",e);
			}
		}




		//处理自游戏升级
		if(!pmutil.isnullorEmpty(gameversionutil.getGame_download())&&!pmutil.isnullorEmpty(agentversionutil.getGame_download())){
			//两个配置文件都配置了子游戏升级   取配置版本最高
			try{
				gamedownloadversion=Integer.parseInt(gameversionutil.getGame_version());
				gamedownloadurl=gameversionutil.getGame_download();
				if(Integer.parseInt(agentversionutil.getGame_version())>gamedownloadversion){
					gamedownloadversion=Integer.parseInt(agentversionutil.getGame_version());
					gamedownloadurl=agentversionutil.getGame_download();

				};
			}catch (Exception e){

				Logger.e("子游戏配置version格式版本问题",e);
			}



		}else{
			try{
				if(!pmutil.isnullorEmpty(gameversionutil.getGame_download())){
					//两个配置文件都配置了app升级取配置版本最高都
					gamedownloadversion=Integer.parseInt(gameversionutil.getGame_version());
					gamedownloadurl=gameversionutil.getGame_download();
				}
			}catch (Exception e){
				Logger.e("gameversionutil配置子游戏 version格式版本问题",e);
			}
			try{

				if(!pmutil.isnullorEmpty(agentversionutil.getGame_download())){
					gamedownloadversion=Integer.parseInt(agentversionutil.getGame_version());
					gamedownloadurl=agentversionutil.getGame_download();
				}
			}catch (Exception e){
				Logger.e("gameversionutil配置子游戏 version格式版本问题",e);
			}
		}


		int AppVersioncode = 0;

		String apkversion = getAllFilename("appversion");
		//
		if (pmutil
				.isnullorEmpty(apkversion)) {

		} else {
			AppVersioncode = Integer
					.parseInt(apkversion);
		}

		// 版本
		if (AppVersioncode > appdownloadversion) {
			apputil.code = 1;
		} else {
			apputil.code = 0;
		}

		boolean isupdate=false;

		if (appdownloadversion > AppVersioncode) {
			progressBar.setVisibility(View.VISIBLE);
			inittext.setText("下载apk安装包...");
			isupdate = true;
			doNewVersionUpdate(appdownloadurl+"?a="+System.currentTimeMillis());

		}

		if(!isupdate){

			String urlpath = SpUtil.getStringSharedPerference(sp, "urlpath");
			String purl = urlpath + File.separator + Settingutil.initfile;

			System.out.println("purl=" + purl);

			versionbean versd = pullxml1(purl);

			String gameid=getAllFilename("gameid");
			if(!pmutil.isnullorEmpty(gameid)){
				versd.setGameid(gameid);
			}

			int xmlgamecode = Integer.parseInt(versd.getVersion());

			if (gamedownloadversion > xmlgamecode) {
				inittext.setText("正在升级版本...");
				progressBar.setVisibility(View.VISIBLE);

				updatezip(gamedownloadurl+"?a="+System.currentTimeMillis());


			} else {

				handlerend1();

			}


		}

	}
	public void inith5data(){
		String url = SpUtil.getStringSharedPerference(Shared, "urlpath");

		url = url + File.separator + Settingutil.initfile+ File.separator+"app_data.js";
		System.out.println("初始化前数据"+ Fileutils.readFile(url));

		StringBuffer buffer=new StringBuffer();


		String app_version="var app_version=1;";//初始化框架加载方式
		buffer.append(app_version);



		String app_gameconfig = getAllFilename("gameconfig");
		app_gameconfig="var app_gameconfig='"+app_gameconfig+"';";
		buffer.append(app_gameconfig);

		String app_gamedir = getAllFilename("gamedir");
		app_gamedir="var app_gamedir='"+app_gamedir+"';";
		buffer.append(app_gamedir);


		String app_gamestart = getAllFilename("gamestart");
		app_gamestart="var app_gamestart='"+app_gamestart+"';";
		buffer.append(app_gamestart);


		String app_agent = getAllFilename("agent");
		app_agent="var app_agent='"+app_agent+"';";
		buffer.append(app_agent);


		String app_appversion = getAllFilename("appversion");
		app_appversion="var app_appversion='"+app_appversion+"';";
		buffer.append(app_appversion);


		String app_market = getAllFilename("market");
		app_market="var app_market='"+app_market+"';";
		buffer.append(app_market);


		String app_channel = getAllFilename("channel");
		app_channel="var app_channel='"+app_channel+"';";
		buffer.append(app_channel);

		String app_invitationcode = getAllFilename("tuiguang");
		if(!pmutil.isnullorEmpty(app_invitationcode)){
			app_invitationcode="var app_invitationcode='"+app_invitationcode+"';";

		}else{
			app_invitationcode="var app_invitationcode='';";
			System.out.println("app_invitationcode"+app_invitationcode);
		}

		buffer.append(app_invitationcode);

		String app_Launchtype = "0";
		app_Launchtype="var app_Launchtype='"+app_Launchtype+"';";
		buffer.append(app_Launchtype);


		String app_gamename = getAllFilename("gamestart");
		app_gamename="var app_gamename='"+app_gamename+"';";
		buffer.append(app_gamename);

		String app_getwifisignalLevel="var app_getwifisignalLevel=1;";
		buffer.append(app_getwifisignalLevel);


		//Fileutils.writeToFile(buffer.toString(),url);

		Fileutils.modifyFile(url,buffer.toString(),false);

		System.out.println("初始化后数据"+Fileutils.readFile(url));




	}

	@SuppressLint("HandlerLeak")
	Handler hanler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			int what = msg.what;

			switch (what) {
				case 1:

					inith5data();


					apputil.activityname ="";
					Intent in = new Intent();
					in.setClass(weclomeactivity1.this, webviewActivity.class);
					startActivity(in);
					finish();
					break;
				case 2:
					inittext.setText("正在升级版本...");
					textView1.setText("");
					hanler.sendEmptyMessageDelayed(disend, 1000);
					break;
				case 3:
					if(!weclomeactivity1.this.isFinishing()){
						if (m_progressDlg1 != null) {
							if (m_progressDlg1.isShowing()) {
								m_progressDlg1.cancel();
							}

						}
					}


					inittext.setText("正在检测新版本...");
					download();

					break;

				case 4:
					inittext.setText("正在解压中...");
					break;
				case 5:

					initdailog();
					break;
				case 6:
					showMissingsettingDialog();

					break;
				default:
					break;
			}
			super.handleMessage(msg);
		}
	};

	static SharedPreferences Shared;
	private IWXAPI api;

	String packnameclass;

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@SuppressLint({ "ShowToast" })
		@Override
		public void handleMessage(Message msg) {
			int success = msg.what;

			Toast.makeText(weclomeactivity1.this, "--" + success, Toast.LENGTH_LONG).show();
			if (success != 1) {

				Wxistrue.isshare = true;

				Wxistrue.isphotoshare = true;

			}

			switch (msg.what) {
				case 1:

					if (Shared == null) {

					}
					userbean bean = new userbean();

					String openid = SpUtil.getStringSharedPerference(Shared,
							"openid");
					bean.setOpenid(openid);

					String headimgurl = SpUtil.getStringSharedPerference(Shared,
							"headimgurl");
					bean.setHeadimgurl(headimgurl);

					String nickname = SpUtil.getStringSharedPerference(Shared,
							"nickname");
					nickname = nickname.replaceAll("'", "");
					bean.setNickname(nickname);

					String sex = SpUtil.getStringSharedPerference(Shared, "sex");
					bean.setSex(sex);

					String city = SpUtil.getStringSharedPerference(Shared, "city");
					bean.setCity(city);

					String province = SpUtil.getStringSharedPerference(Shared,
							"province");
					bean.setProvince(province);

					String unionid = SpUtil.getStringSharedPerference(Shared,
							"unionid");
					bean.setUnionid(unionid);

					Wxistrue.islogin = true;

					// String sharelogin = "javascript:sharelogin(" + "'" + openid
					// + "'" + ",'" + headimgurl + "'" + ",'" + nickname + "'"
					// + ",'" + sex + "'" + ",'" + city + "'" + ",'"
					// + province + "'" + ",'" + unionid + "'" + ");";
					// webviewjh(sharelogin);

					Gson gson = new Gson();
					String data = gson.toJson(bean);

					// Toast.makeText(weclomeactivity1.this, data, 1).show();

					Intent result = new Intent(packnameclass,
							Uri.parse("content://" + ""));
					result.addCategory(Intent.CATEGORY_DEFAULT);
					result.putExtra("data", data);
					setResult(Activity.RESULT_OK, result);
					finish();

					// Intent result = new Intent();
					//
					// // result.setComponent(new
					// // ComponentName("com.example.ceshiintent",
					// // packnameclass));
					//
					// result.putExtra("data", data);
					// setResult(Activity.RESULT_OK, result);
					// finish();

					//
					// //in.setClassName(MainActivity.this, packnameclass);
					// // Intent result = new Intent("com.example.appsend",
					// // Uri.parse("content://result_uri"));
					//
					// in.putExtra("sharelogin", sharelogin);
					// //startActivity(in);
					// setResult(RESULT_OK, in);
					// finish();

					break;
				default:
					break;
			}
			super.handleMessage(msg);
		}
	};
	RelativeLayout relative1;
	private Context mContext;


	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Util.verifyStoragePermissions(this);
		if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
			finish();
			return;
		}

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		/**
		 * 保持屏幕唤醒 不锁屏
		 *
		 */
		// getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
		// WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		setContentView(R.layout.welcome);

		CsvFormatStrategy formatStrategy=CsvFormatStrategy.newBuilder()
				.tag("niuniu")
				.build();//修改默认配置
		Logger.addLogAdapter(new DiskLogAdapter(formatStrategy));//保持日志文件
		Logger.addLogAdapter(new AndroidLogAdapter(){
			@Override
			public boolean isLoggable(int priority, @Nullable String tag) {
				//s是否开启打印功能
				return false;
			}
		});
		getclassname();


		mContext = this;
		UMGameAgent.setDebugMode(true);
		UMGameAgent.init(this);
		// Deprecated UMGameAgent.setPlayerLevel("LV.01");
		UMGameAgent.setPlayerLevel(1);
		// UMGameAgent.setSessionContinueMillis(1000);
		// UMGameAgent.startWithConfigure(
		// new UMAnalyticsConfig(mContext, "4f83c5d852701564c0000011", "Umeng",
		// EScenarioType.E_UM_GAME));
		MobclickAgent.setScenarioType(mContext, EScenarioType.E_UM_NORMAL);

		relative1 = (RelativeLayout) findViewById(R.id.relative1);
		Shared = SpUtil.getSharePerference(weclomeactivity1.this);

		api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);

		init1();

	}
	private void getclassname() {
		ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
		RunningTaskInfo cinfo = runningTasks.get(0);
		ComponentName component = cinfo.topActivity;
		System.out.println("current activity is " + component.getClassName());
		apputil.activityname = component.getClassName();

	}

	/**
	 * 登录微信
	 */
	private void WXLogin() {

		if (!api.isWXAppInstalled()) {
			Toast.makeText(weclomeactivity1.this, "您还未安装微信客户端", Toast.LENGTH_LONG).show();
			return;
		}

		login();

	}

	public void login() {
		WXEntryActivity.setshareHandler(handler);
		api = WXAPIFactory.createWXAPI(weclomeactivity1.this, Constants.APP_ID,
				true);
		api.registerApp(Constants.APP_ID);
		SendAuth.Req req = new SendAuth.Req();
		req.scope = "snsapi_userinfo";
		req.state = "wechat_sdk_demo";
		api.sendReq(req);

	}

	@SuppressLint("InvalidWakeLockTag")
	private void init1() {

		/*
		 * *
		 * 方法二
		 */
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		// m_wklk = pm.newWakeLock
		// (PowerManager.ACQUIRE_CAUSES_WAKEUP |
		// PowerManager.SCREEN_DIM_WAKE_LOCK, "Tag");
		//

		m_wklk = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "cn");

		m_wklk.setReferenceCounted(false);

		m_wklk.acquire();// 设置保持唤醒

		initwebviewutil.getInstance().sethandler(hanler);

		Settingutil.initfile = getAllFilename("gamestart");// 游戏解压之后目录

		Settingutil.filestart = getAllFilename("gamedir");// 父级目录

		System.out.println("Settingutil.initfile=" + Settingutil.initfile);
		System.out.println("Settingutil.filestart=" + Settingutil.filestart);

		Intent in1 = getIntent();
		if (in1 != null) {
			Bundle bundle = in1.getExtras();

			if (bundle != null) {
				packnameclass = bundle.getString("packname");
				System.out.println("packname=" + packnameclass);

				if (!pmutil.isnullorEmpty(packnameclass)) {
					Wxistrue.islogin = false;// 暂停授权登陆
					apputil.wxtype = 2;
					WXLogin();
					setIntent(null);

				} else {
					if (!pmutil.isnullorEmpty(Settingutil.initfile)
							&& !pmutil.isnullorEmpty(Settingutil.filestart)) {

						init();
					} else {
						showMissingsettingDialog();

					}

				}

			} else {

				if (!pmutil.isnullorEmpty(Settingutil.initfile)
						&& !pmutil.isnullorEmpty(Settingutil.filestart)) {

					init();
				} else {
					showMissingsettingDialog();

				}

			}
		} else {
			System.out.println("Intent为空");
			if (!pmutil.isnullorEmpty(Settingutil.initfile)
					&& !pmutil.isnullorEmpty(Settingutil.filestart)) {

				init();
			} else {
				System.out.println("Settingutil.initfile为空");
				showMissingsettingDialog();

			}
		}

		okclient = new OkHttpClient.Builder()
				.connectTimeout(20, TimeUnit.SECONDS)
				.readTimeout(20, TimeUnit.SECONDS).build();

	}

	@Override
	protected void onDestroy() {
		if (m_wklk != null) {
			try {
				m_wklk.release(); // 解除保持唤醒
			} catch (Exception e) {
				// TODO: handle exception
			}

		}
		super.onDestroy();

	}

	@Override
	protected void onResume() {

		super.onResume();
		if (m_wklk != null) {
			m_wklk.acquire(); // 保持唤醒
		}

		MobclickAgent.onPageStart("welcomeactivity1");
		//统计页面(仅有Activity的应用中SDK自动调用，不

		// 集成基本统计分析,初始化 Session
		UMGameAgent.onResume(mContext);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		if (m_wklk != null) {
			try {
				m_wklk.release(); // 解除保持唤醒
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		MobclickAgent.onPageEnd("welcomeactivity1");
		// //集成基本统计分析, 结束 Session
		UMGameAgent.onPause(mContext);

	}

	private void init() {
		relative1.setVisibility(View.VISIBLE);
		System.out.println("Settingutil.initfile=" + Settingutil.initfile);
		System.out.println("Settingutil.filestart=" + Settingutil.filestart);
		String gameconfig = getAllFilename("gameconfig");
		gameconfig = gameconfig.replaceAll("-", "/");

		if (!pmutil.isnullorEmpty(gameconfig)) {
			Gamesettingurl.configofficialurl = "http://" + gameconfig + ".txt";
			System.out.println("Gamesettingurl.configofficialurl="
					+ Gamesettingurl.configofficialurl);
		}


		progressBar = (ProgressBar) findViewById(R.id.progressBar1);
		m_mainHandler = new Handler();
		inittext = (TextView) findViewById(R.id.inittext);
		textView1 = (TextView) findViewById(R.id.textView1);

		if (!hasPermission(permissons)) {

			PermissionGen.needPermission(weclomeactivity1.this, 33, permissons);
		} else {

			hanler.sendEmptyMessage(5);
			sp = SpUtil.getSharePerference(Myapplication.application);
			Boolean istrue = SpUtil.isFirst(sp);

			if (istrue) {
				System.out.println("不是第一次");

				String urlpath1 = SpUtil.getStringSharedPerference(sp,
						"upurlpath") + File.separator + Settingutil.filestart;
				File file = new File(urlpath1);

				if (file.exists()) {

					versionbean ver = null;
					try {

						ver = pullassetxml(getAssets().open(
								Settingutil.kfile + File.separator
										+ "version.xml"));
					} catch (IOException e) {

						e.printStackTrace();

					}

					SpUtil.setStringSharedPerference(sp, "urlpath", urlpath1);

					String urlpath = SpUtil.getStringSharedPerference(sp,
							"urlpath");

					String purl = urlpath + File.separator
							+ Settingutil.initfile;

					System.out.println("解压目录" + purl);

					File fie = new File(purl);

					if (fie.exists()) {

						System.out.println("----" + purl);

						versionbean versd = pullxml1(purl);
						String gameid=getAllFilename("gameid");
						if(!pmutil.isnullorEmpty(gameid)){
							versd.setGameid(gameid);
						}

						int assetversion = Integer.parseInt(ver.getVersion());

						try{

							if(versd!=null&&!pmutil.isnullorEmpty(versd.getVersion())){

								int sdversion = Integer.parseInt(versd.getVersion());
								System.out.println("sdversion=" + sdversion);

								System.out.println("assetversion=" + assetversion);

								if (assetversion > sdversion) {
									System.out.println("2");
									copyinit();

								} else {

									copyasset();
								}


							}else{
								copyinit();
							}

						}catch(Exception e){
							copyinit();
						}
					} else {
						copyinit();
					}

				} else {
					copyinit();
				}

			} else {
				copyasset();
			}

		}

	}

	public void copyinit() {
		new Thread() {
			public void run() {

				initwebviewutil.getInstance().init();
			};

		}.start();
	}

	public void copyasset() {
		new Thread() {
			public void run() {

				initwebviewutil.getInstance().isfirst();
			};

		}.start();
	}

	private void initdailog() {
		if (m_progressDlg1 == null) {
			m_progressDlg1 = new ProgressDialog(this);
		}
		m_progressDlg1.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		// 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确
		m_progressDlg1.setIndeterminate(false);
		m_progressDlg1.setCanceledOnTouchOutside(false);

		m_progressDlg1.setTitle("正在初始化…");
		m_progressDlg1.setMessage("请稍候...");

		if (!weclomeactivity1.this.isFinishing()) {

			m_progressDlg1.show();
		}

		// SHA1: E1:11:0A:7C:D6:81:BC:31:FE:38:61:01:3C:C5:28:97:57:AD:94:FD
		// 82:CB:24:28:2B:CB:97:F0:8F:23:78:C7:21:3D:74:D4:74:6B:9F:91
	}

	@PermissionSuccess(requestCode = 33)
	public void filstsucces() {
		System.out.println("允许");

		hanler.sendEmptyMessage(5);
		copyasset();
	}

	@PermissionFail(requestCode = 33)
	public void filstfail() {


		List<String> nopermission = new ArrayList<String>();
		// String[] nopermission=null;
		for (int i = 0; i < permissons.length; i++) {
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					permissons[i])) {

				nopermission.add(permissons[i]);

				// final String permission = carpermission[i];
				// 未勾选不再提示

				System.out.println("拒绝");
			} else {
				// 勾选不再提示
				if (ContextCompat.checkSelfPermission(this,
						permissons[i]) == PackageManager.PERMISSION_DENIED) {
					showMissingPermissionDialog();
					break;
				}
			}
		}
		if (nopermission.size() > 0) {

			final String[] persions = new String[nopermission.size()];

			for (int i = 0; i < nopermission.size(); i++) {
				persions[i] = nopermission.get(i);
			}

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("提示");
			builder.setMessage("亲,当前应用缺少必要权限。不打开将无法使用");

			// 拒绝, 退出应用
			builder.setNegativeButton("退出",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();

						}
					});

			builder.setPositiveButton("打开",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {

							PermissionGen.needPermission(weclomeactivity1.this,
									33, persions);
						}
					});
			builder.show();
		}

	}

	// 配置缺失提示
	private void showMissingsettingDialog(String title) {
		if (!weclomeactivity1.this.isFinishing()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("提示");
			builder.setMessage(title);

			builder.setPositiveButton("退出",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							finish();
						}
					});
			builder.setCancelable(false);
			builder.show();
		}

	}

	// 配置缺失提示
	private void showMissingsettingDialog() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if (!weclomeactivity1.this.isFinishing()&&hasWindowFocus()) {
					System.out.println("有窗口焦点");
					AlertDialog.Builder builder = new AlertDialog.Builder(weclomeactivity1.this);
					builder.setTitle("提示");
					builder.setMessage("您好，获取配置信息失败,检查是否连接网络，请重新启动应用");

					builder.setPositiveButton("退出",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									finish();
								}
							});
					builder.setCancelable(false);
					builder.show();
				}else{
					System.out.println("无窗口焦点");

					AlertDialog.Builder builder = new AlertDialog.Builder(weclomeactivity1.this);
					builder.setTitle("提示");
					builder.setMessage("您好，获取配置信息失败,检查是否连接网络，请重新启动应用");

					builder.setPositiveButton("退出",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog, int which) {
									finish();
								}
							});
					builder.setCancelable(false);
					builder.show();
				}
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {

			case KeyEvent.KEYCODE_BACK:

				dialogexit.show(weclomeactivity1.this, "确定退出",
						new onexitlistener() {
							@Override
							public void paylistener() {

								exitApp();
							}

							@Override
							public void cancellistener() {

							}
						});

				return true;

			default:
				break;
		}

		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 退出程序
	 */
	private void exitApp() {

		finish();
		System.exit(0);
	}

	// 显示缺失权限提示
	private void showMissingPermissionDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("当前应用缺少必要权限。请点击\"设置\"-\"权限\"-打开所需权限。");

		// 拒绝, 退出应用
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				startAppSettings();
			}
		});

		builder.show();
	}

	// 启动应用的设置
	private void startAppSettings() {
		Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
		intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
		startActivity(intent);
	}

	private void download() {

		if (apputil.isNetworkConnected(this)) {
			sp = SpUtil.getSharePerference(Myapplication.application);
			projectpath = SpUtil.getStringSharedPerference(sp, "urlpath");

			String urls = projectpath + File.separator + Settingutil.initfile
					+ File.separator + "version.xml";

			File file = new File(urls);

			if (file.exists()) {
				String purl = projectpath + File.separator
						+ Settingutil.initfile;
				jsongame1();
			} else {
				handlerend1();
			}
		} else {

			AlertDialog.Builder builder = new Builder(this);
			builder.setTitle("无法链接网络");
			builder.setMessage("网络错误，请设置网络");

			builder.setPositiveButton("退出",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// 获取系统版本号
							finish();

						}
					});
			builder.create().show();
		}

	}

	private void jsongame1() {
		String url = "";
		url = Gamesettingurl.configofficialurl;
		updateapk2(url,1);
	}

	private void updateapk2(String url, final int what) {

		url = url + "?a=" + System.currentTimeMillis();//增加随机参数
		System.out.println("url==" + url);
		CacheControl.Builder builder = new CacheControl.Builder();
		builder.noCache();// 不使用缓存，全部走网络
		CacheControl cacheControl = builder.build();

		Request request1 = new Request.Builder().cacheControl(cacheControl)
				.url(url).build();

		Request request = new Request.Builder().url(url).build();

		okclient.newCall(request1).enqueue(new Callback() {

			@Override
			public void onResponse(Call arg0, Response response)
					throws IOException {

				System.out.println(response.code() + "ss"
						+ response.body().toString());

				if (response.code() == 200) {

					InputStream is = null;
					byte[] buf = new byte[1024];
					is = response.body().byteStream();
					StringBuilder sb = new StringBuilder("");
					int lens = 0;
					//读取文件内容，当文件内容长度大于0时，
					while ((lens = is.read(buf)) > 0) {
						//把字条串连接到尾部
						sb.append(new String(buf, 0, lens));
					}
					is.close();
					final String s=sb.toString();
					System.out.println("长度="+s.length());
					if (s.length() < 30) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								AlertDialog.Builder builder = new AlertDialog.Builder(
										weclomeactivity1.this);
								builder.setTitle("提示");
								builder.setMessage(s);
								builder.setPositiveButton("退出",
										new DialogInterface.OnClickListener() {
											@Override
											public void onClick(
													DialogInterface dialog,
													int which) {
												finish();
											}
										});
								builder.show();
							}
						});
					} else {
						try {
							JSONObject json = new JSONObject(s);
							System.out.println("---" + json.toString());
							Message msg=new Message();
							msg.what=what;
							Bundle bundle=new Bundle();
							bundle.putString("msg",s);
							Logger.t("msg").v(s);
							msg.setData(bundle);
							hanlerq1.sendMessage(msg);
						} catch (Exception e) {
							e.printStackTrace();
							hanler.sendEmptyMessage(6);
						}
					}
				} else {
					hanler.sendEmptyMessage(6);
				}
			}

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				System.out.println("获取数据失败");
				hanler.sendEmptyMessage(6);
			}
		});

	}

	versionagentlist list1;
	Gameversiontxt gameversiontxt;
	JsonRootBean mJsonRootBean;
	Agentlist    magentlist;
	Gamelist     mgamelist;

	/**
	 * 提示更新新版本
	 */
	private void doNewVersionUpdate(String url) {
		System.out.println(url);
		try {
			downFile(url); // 开始下载
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void downFile(final String url) {

		new Thread() {
			public void run() {
				// 替换为OkHttp客户端，修复Apache HttpClient兼容性问题
				if (okclient == null) {
					okclient = new OkHttpClient();
				}
				
				Request request = new Request.Builder().url(url).build();
				
				try {
					Response response = okclient.newCall(request).execute();
					
					if (!response.isSuccessful()) {
						throw new IOException("下载失败，HTTP状态码: " + response.code());
					}

					long length = response.body().contentLength();
					if (progressBar != null) {
						progressBar.setMax((int) length);
					}

					final int sum = (int) length;

					InputStream is = response.body().byteStream();
					FileOutputStream fileOutputStream = null;
					
					// 在外层声明变量，避免作用域问题
					String apkFilePath = "";
					
					if (is != null) {
						// 修复：使用应用私有目录，兼容Android 10+的存储限制
						File downloadDir = new File(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "apk");
						if (!downloadDir.exists()) {
							downloadDir.mkdirs();
						}
						File file = new File(downloadDir, m_appNameStr);
						
						// 记录文件路径供安装时使用
						apkFilePath = file.getAbsolutePath();
						
						fileOutputStream = new FileOutputStream(file);

						byte[] buf = new byte[1024];
						int ch = 0;
						int count = 0;

						NumberFormat nf = NumberFormat.getInstance();
						nf.setMaximumFractionDigits(2);// 保留一位小数
						double msum = (sum / 1024.0 / 1024.0);
						final String msums = nf.format(msum) + " MB";

						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);

							count += ch;

							final int num = count;

							if (length > 0) {
								if (progressBar != null) {
									progressBar.setProgress(num);
								}

								hanler.post(new Runnable() {
									@SuppressLint("SetTextI18n")
									@Override
									public void run() {
										NumberFormat nf = NumberFormat.getInstance();
										nf.setMaximumFractionDigits(2);// 保留一位小数
										double num1 = (num / 1024.0 / 1024.0);
										final String nums = nf.format(num1) + " MB";
										textView1.setText("" + nums + "/" + msums);
									}
								});
							}
						}
						
						// 将文件操作移到if块内，确保fileOutputStream不为null
						fileOutputStream.flush();
						fileOutputStream.close();
						
						// 保存APK文件路径供安装使用
						apkFilePathForInstall = apkFilePath;
						
						down(); // 告诉HANDER已经下载完成了，可以安装了
					}
					
					down(); // 告诉HANDER已经下载完成了，可以安装了
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	/**
	 * 告诉HANDER已经下载完成了，可以安装了
	 */
	private void down() {

		m_mainHandler.post(new Runnable() {
			public void run() {
				update1();
			}
		});
	}

	/**
	 * 安装程序 - 修复兼容Android 7.0+和10+
	 */
	void update1() {
		if (apkFilePathForInstall.isEmpty()) {
			Toast.makeText(this, "APK文件路径错误", Toast.LENGTH_SHORT).show();
			return;
		}
		
		File apkFile = new File(apkFilePathForInstall);
		if (!apkFile.exists()) {
			Toast.makeText(this, "APK文件不存在", Toast.LENGTH_SHORT).show();
			return;
		}
		
		// Android 8.0+ 需要检查安装权限
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
			if (!getPackageManager().canRequestPackageInstalls()) {
				// 跳转到设置页面开启安装权限
				Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
				intent.setData(Uri.parse("package:" + getPackageName()));
				startActivity(intent);
				Toast.makeText(this, "请开启允许安装未知来源应用权限", Toast.LENGTH_LONG).show();
				return;
			}
		}
		
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		
		// Android 7.0+ 需要使用FileProvider
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			Uri apkUri = android.support.v4.content.FileProvider.getUriForFile(
					this, 
					getPackageName() + ".fileprovider", 
					apkFile);
			intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
		} else {
			// Android 6.0及以下使用传统方式
			intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
		}
		
		try {
			startActivity(intent);
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, "安装APK失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
		}
		//android.os.Process.killProcess(android.os.Process.myPid());// 安装后打开
	}

	public void handlerend1() {
		if (progressBar != null) {
			progressBar.setMax(100);
			progressBar.setProgress(100);
		}

		hanler.sendEmptyMessageDelayed(disend, 500);
	}

	private void updatezip(String url) {

		try {
			run(url);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private OkHttpClient okclient;
	protected String destFileDir;
	public void run(final String url) {

		Request request = new Request.Builder().url(url).build();
		okclient.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call arg0, IOException throwable) {
				throwable.printStackTrace();

				handlerend1();
			}

			@SuppressWarnings("resource")
			@Override
			public void onResponse(Call arg0, Response response)
					throws IOException {

				long length = response.body().contentLength();
				progressBar.setMax((int) length);

				if (!response.isSuccessful())
					throw new IOException("Unexpected code " + response);
				Headers responseHeaders = response.headers();
				for (int i = 0; i < responseHeaders.size(); i++) {
					System.out.println(responseHeaders.name(i) + ": "
							+ responseHeaders.value(i));
				}
				if (response.code() == 200) {
					InputStream is = null;
					byte[] buf = new byte[2048];
					int len = 0;
					FileOutputStream fos = null;
					is = response.body().byteStream();
					destFileDir = Objects.requireNonNull(Myapplication.application.getExternalFilesDir(null))
							.getAbsolutePath()
							+ File.separator
							+ "dowlod_zip";
					Log.i("path1", destFileDir);

					File dir = new File(destFileDir);
					Log.i("dir",dir.getPath());
					if (!dir.exists()) {

						Boolean rTemp = dir.mkdirs();
						Log.i("mkdir",rTemp.toString());
					}

					final File file = new File(dir, System.currentTimeMillis()+"Projects.zip");
					System.out.println(file.getAbsolutePath());
					fos = new FileOutputStream(file);
					int count = 0;
					while ((len = is.read(buf)) != -1) {
						fos.write(buf, 0, len);
						count += len;
						if (length > 0) {
							progressBar.setProgress(count);
						}
					}

					fos.flush();
					fos.close();

					hanler.sendEmptyMessage(4);
					try {
						new Thread() {
							public void run() {
								try {
									Fileutils.deleteDir(projectpath + File.separator+Settingutil.initfile);//删除当前解压文件
									System.out.println("删除完成");
								}catch(Exception e){
									e.printStackTrace();
								}

								try {
									System.out.println("解压");
									ZipUtils.upZipFile1(file, projectpath + File.separator);

									try {
										System.out.println("删除destFileDir");
										Fileutils.deleteDir(destFileDir);//删除游戏zip包及文件
									}catch(Exception e){
										e.printStackTrace();
									}
									handlerend1();
								} catch (ZipException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									showMissingsettingDialog();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
									showMissingsettingDialog();
								}
							}

						}.start();
					} catch (Exception e) {
						showMissingsettingDialog();
					}
					System.out.println(file.getAbsolutePath());
				} else {
					showMissingsettingDialog();
				}
			}

		});
	}

	private versionbean pullassetxml(InputStream inputStream) {
		versionbean version2 = new versionbean();
		try {
			XmlPullParser parser = Xml.newPullParser();
			// 2.设置解析的文件流
			parser.setInput(inputStream, "utf-8");
			// 3.得到事件类型(START_DOCUMENT,END_DOCUMENT,START_TAG, END_TAG,
			// TEXT, etc.)
			int type = parser.getEventType();
			// 一直读到文档结尾
			while (type != XmlPullParser.END_DOCUMENT) {

				switch (type) {
					case XmlPullParser.START_TAG:
						// 得到标签的名字
						String tag_name = parser.getName();
						if ("agent".equals(tag_name)) {

							String agentid = parser.getAttributeValue(null, "id");
							System.out.println("agentid=" + agentid);
							version2.setAgentid(agentid);

						} else if ("game".equals(tag_name)) {
							String gameid = parser.getAttributeValue(null, "id");
							System.out.println("gameid=" + gameid);
							version2.setGameid(gameid);
						} else if ("version".equals(tag_name)) {

							String version = parser
									.getAttributeValue(null, "value");
							System.out.println("version=" + version);
							version2.setVersion(version);
						}

						break;
					default:
						break;

				}
				// 继续往下一个事件解析
				type = parser.next();
			}

		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version2;
	}

	private versionbean pullxml1(String urlpath) {
		versionbean version1 = new versionbean();
		try {
			File file = new File(urlpath + File.separator + "version.xml");

			if (file.exists()) {
				FileInputStream inputStream = new FileInputStream(file);
				// 得到解析器
				XmlPullParser parser = Xml.newPullParser();
				// 2.设置解析的文件流
				parser.setInput(inputStream, "utf-8");
				// 3.得到事件类型(START_DOCUMENT,END_DOCUMENT,START_TAG, END_TAG,
				// TEXT, etc.)
				int type = parser.getEventType();
				// 一直读到文档结尾


				while (type != XmlPullParser.END_DOCUMENT) {

					switch (type) {
						case XmlPullParser.START_TAG:
							// 得到标签的名字
							String tag_name = parser.getName();
							if ("agent".equals(tag_name)) {

								String agentid = parser.getAttributeValue(null,
										"id");
								System.out.println("agentid=" + agentid);
								version1.setAgentid(agentid);
								// String id = parser.getAttributeValue(0);
								// 得到属性值id
							} else if ("game".equals(tag_name)) {
								String gameid = parser
										.getAttributeValue(null, "id");
								System.out.println("gameid=" + gameid);
								version1.setGameid(gameid);
							} else if ("version".equals(tag_name)) {

								String version = parser.getAttributeValue(null,
										"value");
								System.out.println("version=" + version);
								version1.setVersion(version);

							} else if ("channel".equals(tag_name)) {

								String channelid = parser.getAttributeValue(null,
										"id");
								version1.setChannelid(channelid);
							}

							break;
						default:
							break;

					}
					// 继续往下一个事件解析
					type = parser.next();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return version1;

	}

	public boolean hasPermission(String... permissions) {
		for (String permission : permissions) {
			if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode,
										   String[] permissions, int[] grantResults) {

		PermissionGen.onRequestPermissionsResult(this, requestCode,
				permissions, grantResults);
	}

	public String getFilenametg(String name) {

		String channelname = "";
		System.out.println("name=" + name);
		try {
			String[] filename = Myapplication.application.getAssets()
					.list(name);

			if (filename.length > 0) {

				System.out.println("目录长度" + filename.length);

				for (int i = 0; i < filename.length; i++) {

					System.out.println("=====" + filename[i]);

					if (filename[i].equals("BoolTest.java")) {
						String[] filename1 = Myapplication.application
								.getAssets().list(
										name + File.separator + filename[i]);
						System.out.println("0--" + filename1.length);
					} else {

						String[] name1 = Myapplication.application.getAssets()
								.list(name + File.separator + filename[i]);
						System.out.println("name1--" + name1.length);
						if(name1.length>=1){
							System.out.println("name1--" + name1[0]);
						}

						if (name1.length >= 0) {
							channelname = filename[i];
						}

					}

				}

			} else {
				System.out.println("找不到目录");
			}

		} catch (IOException e) {

			e.printStackTrace();
		}

		return channelname;

	}

	public String getAllFilename(String name) {

		String channelname = "";
		System.out.println("name=" + name);
		try {
			String[] filename = Myapplication.application.getAssets()
					.list(name);

			if (filename.length > 0) {

				System.out.println("目录长度" + filename.length);

				for (int i = 0; i < filename.length; i++) {

					System.out.println("=====" + filename[i]);

					if (filename[i].equals("BoolTest.java")) {
						String[] filename1 = Myapplication.application
								.getAssets().list(
										name + File.separator + filename[i]);
						System.out.println("0--" + filename1.length);
					} else {

						String[] name1 = Myapplication.application.getAssets()
								.list(name + File.separator + filename[i]);
						System.out.println("name1--" + name1.length);
						if(name1.length>=1){
							System.out.println("name1--" + name1[0]);
						}

						if (name1.length >= 0) {
							channelname = filename[i];
						}

					}

				}

			} else {
				System.out.println("找不到目录");
			}

		} catch (IOException e) {

			e.printStackTrace();
		}

		return channelname;

	}

	public String getchannelname(String name) {
		String channelname = "";
		try {
			String[] filename = Myapplication.application.getAssets()
					.list(name);
			if (filename.length > 0) {

				System.out.println("目录长度" + filename.length);

				for (int i = 0; i < filename.length; i++) {

					System.out.println("=====" + filename[i]);

					if (filename[i].equals("BoolTest.java")) {

					} else {

						if (filename[i].length() > 30) {
							channelname = filename[i];
						}

					}

				}

			}

		} catch (IOException e) {

			e.printStackTrace();
		}

		return channelname;

	}


}
