下载游戏apk,并安装 /*********下载游戏apk,并安装,代码有删减*******************/ package com.chinagames.ChinaGameHall.UI; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.NumberFormat; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.KeyEvent; import android.view.Window; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.chinagames.ChinaGameHall.R; import com.chinagames.ChinaGameHall.Common.BaseControl; import com.chinagames.ChinaGameHall.Common.Common; import com.chinagames.ChinaGameHall.Common.Util; /*** android中国游戏大厅画面 游戏下载和安装页面*/ public class GameDownloadAndInstall extends Activity {// 打印标志private String Tag = "GameDownloadAndInstall";// 获得组建对象private TextView tvname; // 显示游戏名的textview对象private TextView tvprogress; // 游戏下载进度private ProgressBar pb;// 进度条对象private int _progress = 0;// 进度数private String realURL = "";//apk的位置private String gamename = "";//apk的名称private String gameverid = "";// 游戏的版本号public boolean isStop = false;// 是否停止下载// 下载保存的位置,为sdcard下;private String fileName = "";// 保存的文件名称private int fileSize = 1;// 文件大小private File file;// 文件对象的定义private String apkName;// 安装包的包名private String result;// 请求下载的结果信息private boolean isHall = false;// 是否请求的是大厅apkprivate HttpURLConnection conn = null;// 连接对象// new 一个下载类private task task = new task();// 下载进度;int progress = 0;/*** 创建视图页面* * @param state Bundle*/public void onCreate(Bundle state) {super.onCreate(state);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.mainface_gamedownloadprogress);Bundle bundle = getIntent().getExtras();// 接受从三个activity传来的 游戏的id 版本信息,和下载游戏的urlrealURL = bundle.getString("URL");gameid = bundle.getString("gameid");if (gameid.equals("0")) {Util.printLog(Tag, "**is down load hall!");isHall = true;Util.printLog(Tag, "**rejister mApplicationsReceiver success!");}gamename = bundle.getString("gamename");gameverid = bundle.getString("gameverid");if (realURL == "" || realURL.equals("") || gameid == "") {tvname.setText("信息获取错误!");return;}inintContent();task.execute(realURL);}/*** 重新注册监听*/protected void onResume() {super.onResume();}/*** 初始化组件*/public void inintContent() {// 注册监听tvname = (TextView) findViewById(R.id.MainFace_DownLoadingTextView01);tvprogress = (TextView) findViewById(R.id.MainFace_DownLoadingTextView02);pb = (ProgressBar) findViewById(R.id.MainFace_DownLoadingProgressBar01);}/*** 阻止返回键退出,给予提示* * @param keyCode* @param event* @return boolean*/public boolean onKeyDown(int keyCode, KeyEvent event) {switch (keyCode) {case KeyEvent.KEYCODE_BACK:createBackDialog();return false;case KeyEvent.KEYCODE_HOME:return false;}return false;}/*** 确定退出的对话框创建*/public void createBackDialog() {AlertDialog.Builder alert1 = new AlertDialog.Builder(this);alert1.setTitle("取消下载").setMessage("确认取消下载吗?").setPositiveButton("确定",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// 停止下载apkisStop = true;finish();}}).setNegativeButton("返回",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}}).create().show();}/*** 安装刚下载的游戏*/public void installGame() {if (!isStop) {try {// 安装之前写id号(lable-id)防止此次下载不安装下次安装时丢失id信息;writeGameId(BaseControl.CURRENT_APP_NAME, gameid,BaseControl.settings_id);// 安装Uri uri = Uri.parse(fileName);Intent startGameIntent = new Intent(Intent.ACTION_VIEW, uri);startGameIntent.setData(uri);startGameIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);startGameIntent.setClassName("com.android.packageinstaller","com.android.packageinstaller.PackageInstallerActivity");PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, startGameIntent, 0);startActivity(startGameIntent);BaseControl.isAppInstallByMobile = true;finish();} catch (Exception e) {e.printStackTrace();Common.getSureDialog(GameDownloadAndInstall.this, "提示","此文件不能安装!");}}}/*** 异步下载apk类* */private class task extends AsyncTask<String, String, String> {/*** 异步线程入口*/protected String doInBackground(String... params) {String pre = params[0];try {if (pre.contains("http://")) {URL sourceUrl;try {sourceUrl = new URL(pre);fileName = sourceUrl.getFile();fileName = fileName.substring(fileName.lastIndexOf('/') + 1);apkName = fileName;fileName = BaseControl.HALL_APK_PATH + apkName;File savaFile = new File(BaseControl.HALL_APK_PATH);if (!savaFile.isDirectory()) {savaFile.mkdir();}FileOutputStream fos = new FileOutputStream(fileName);int read = 0;byte[] buffer = new byte[1024];conn = (HttpURLConnection) sourceUrl.openConnection();conn.setDoInput(true);conn.connect();fileSize = conn.getContentLength();InputStream is = conn.getInputStream();int progress = 0;do {read = is.read(buffer);if (read > 0) {// 循环读取写游戏数据到sd卡;读取过程中发送进度消息;fos.write(buffer, 0, read);progress += read;publishProgress("" + progress);}} while (read != -1);fos.close();is.close();conn.disconnect();if (progress != fileSize) {tvname.setText("下载结束!");return "下载结束";}} catch (Exception e) {e.printStackTrace();tvname.setText("下载出现异常!请检查SD卡安装是否正常!");return "异常";}} else {}} catch (Exception ex) {ex.printStackTrace();} finally {}return "任务结束";}/*** 根据异步线程结果发送消息跟新url* * */protected void onPostExecute(String result) {super.onPostExecute(result);if (result.equals("下载结束")) {Toast.makeText(GameDownloadAndInstall.this, result,Toast.LENGTH_SHORT).show();}}/*** 最先执行,在UI线程中被系统调用*/protected void onPreExecute() {super.onPreExecute();Toast.makeText(GameDownloadAndInstall.this, "开始执行下载任务 ",Toast.LENGTH_SHORT).show();}/*** 更新界面操作,在收到更新消息后,在UI线程中被系统调用*/protected void onProgressUpdate(String... values) {super.onProgressUpdate(values);int progress = Integer.parseInt(values[0]);if (progress >= fileSize) {// 调用安装方法installGame();}NumberFormat numberFormat = NumberFormat.getInstance();// 设置精确到小数点后2位numberFormat.setMaximumFractionDigits(0);String result = numberFormat.format((float) progress/ (float) fileSize * 100);tvname.setText(apkName + " 下载中...");tvprogress.setText(result + "%");pb.setProgress(Integer.parseInt(result));}}/*** 程序释放*/public void onDestroy() {super.onDestroy();if (task != null) {task.cancel(true);}Util.printLog(Tag, "onDestroy..isAppInstallByMobile:"+ BaseControl.isAppInstallByMobile);} } 下载游戏apk,并安装 /*********下载游戏apk,并安装,代码有删减*******************/ package com.chinagames.ChinaGameHall.UI; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.text.NumberFormat; import android.app.Activity; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.KeyEvent; import android.view.Window; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.chinagames.ChinaGameHall.R; import com.chinagames.ChinaGameHall.Common.BaseControl; import com.chinagames.ChinaGameHall.Common.Common; import com.chinagames.ChinaGameHall.Common.Util; /*** android中国游戏大厅画面 游戏下载和安装页面*/ public class GameDownloadAndInstall extends Activity {// 打印标志private String Tag = "GameDownloadAndInstall";// 获得组建对象private TextView tvname; // 显示游戏名的textview对象private TextView tvprogress; // 游戏下载进度private ProgressBar pb;// 进度条对象private int _progress = 0;// 进度数private String realURL = "";//apk的位置private String gamename = "";//apk的名称private String gameverid = "";// 游戏的版本号public boolean isStop = false;// 是否停止下载// 下载保存的位置,为sdcard下;private String fileName = "";// 保存的文件名称private int fileSize = 1;// 文件大小private File file;// 文件对象的定义private String apkName;// 安装包的包名private String result;// 请求下载的结果信息private boolean isHall = false;// 是否请求的是大厅apkprivate HttpURLConnection conn = null;// 连接对象// new 一个下载类private task task = new task();// 下载进度;int progress = 0;/*** 创建视图页面* * @param state Bundle*/public void onCreate(Bundle state) {super.onCreate(state);requestWindowFeature(Window.FEATURE_NO_TITLE);setContentView(R.layout.mainface_gamedownloadprogress);Bundle bundle = getIntent().getExtras();// 接受从三个activity传来的 游戏的id 版本信息,和下载游戏的urlrealURL = bundle.getString("URL");gameid = bundle.getString("gameid");if (gameid.equals("0")) {Util.printLog(Tag, "**is down load hall!");isHall = true;Util.printLog(Tag, "**rejister mApplicationsReceiver success!");}gamename = bundle.getString("gamename");gameverid = bundle.getString("gameverid");if (realURL == "" || realURL.equals("") || gameid == "") {tvname.setText("信息获取错误!");return;}inintContent();task.execute(realURL);}/*** 重新注册监听*/protected void onResume() {super.onResume();}/*** 初始化组件*/public void inintContent() {// 注册监听tvname = (TextView) findViewById(R.id.MainFace_DownLoadingTextView01);tvprogress = (TextView) findViewById(R.id.MainFace_DownLoadingTextView02);pb = (ProgressBar) findViewById(R.id.MainFace_DownLoadingProgressBar01);}/*** 阻止返回键退出,给予提示* * @param keyCode* @param event* @return boolean*/public boolean onKeyDown(int keyCode, KeyEvent event) {switch (keyCode) {case KeyEvent.KEYCODE_BACK:createBackDialog();return false;case KeyEvent.KEYCODE_HOME:return false;}return false;}/*** 确定退出的对话框创建*/public void createBackDialog() {AlertDialog.Builder alert1 = new AlertDialog.Builder(this);alert1.setTitle("取消下载").setMessage("确认取消下载吗?").setPositiveButton("确定",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// 停止下载apkisStop = true;finish();}}).setNegativeButton("返回",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {}}).create().show();}/*** 安装刚下载的游戏*/public void installGame() {if (!isStop) {try {// 安装之前写id号(lable-id)防止此次下载不安装下次安装时丢失id信息;writeGameId(BaseControl.CURRENT_APP_NAME, gameid,BaseControl.settings_id);// 安装Uri uri = Uri.parse(fileName);Intent startGameIntent = new Intent(Intent.ACTION_VIEW, uri);startGameIntent.setData(uri);startGameIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);startGameIntent.setClassName("com.android.packageinstaller","com.android.packageinstaller.PackageInstallerActivity");PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, startGameIntent, 0);startActivity(startGameIntent);BaseControl.isAppInstallByMobile = true;finish();} catch (Exception e) {e.printStackTrace();Common.getSureDialog(GameDownloadAndInstall.this, "提示","此文件不能安装!");}}}/*** 异步下载apk类* */private class task extends AsyncTask<String, String, String> {/*** 异步线程入口*/protected String doInBackground(String... params) {String pre = params[0];try {if (pre.contains("http://")) {URL sourceUrl;try {sourceUrl = new URL(pre);fileName = sourceUrl.getFile();fileName = fileName.substring(fileName.lastIndexOf('/') + 1);apkName = fileName;fileName = BaseControl.HALL_APK_PATH + apkName;File savaFile = new File(BaseControl.HALL_APK_PATH);if (!savaFile.isDirectory()) {savaFile.mkdir();}FileOutputStream fos = new FileOutputStream(fileName);int read = 0;byte[] buffer = new byte[1024];conn = (HttpURLConnection) sourceUrl.openConnection();conn.setDoInput(true);conn.connect();fileSize = conn.getContentLength();InputStream is = conn.getInputStream();int progress = 0;do {read = is.read(buffer);if (read > 0) {// 循环读取写游戏数据到sd卡;读取过程中发送进度消息;fos.write(buffer, 0, read);progress += read;publishProgress("" + progress);}} while (read != -1);fos.close();is.close();conn.disconnect();if (progress != fileSize) {tvname.setText("下载结束!");return "下载结束";}} catch (Exception e) {e.printStackTrace();tvname.setText("下载出现异常!请检查SD卡安装是否正常!");return "异常";}} else {}} catch (Exception ex) {ex.printStackTrace();} finally {}return "任务结束";}/*** 根据异步线程结果发送消息跟新url* * */protected void onPostExecute(String result) {super.onPostExecute(result);if (result.equals("下载结束")) {Toast.makeText(GameDownloadAndInstall.this, result,Toast.LENGTH_SHORT).show();}}/*** 最先执行,在UI线程中被系统调用*/protected void onPreExecute() {super.onPreExecute();Toast.makeText(GameDownloadAndInstall.this, "开始执行下载任务 ",Toast.LENGTH_SHORT).show();}/*** 更新界面操作,在收到更新消息后,在UI线程中被系统调用*/protected void onProgressUpdate(String... values) {super.onProgressUpdate(values);int progress = Integer.parseInt(values[0]);if (progress >= fileSize) {// 调用安装方法installGame();}NumberFormat numberFormat = NumberFormat.getInstance();// 设置精确到小数点后2位numberFormat.setMaximumFractionDigits(0);String result = numberFormat.format((float) progress/ (float) fileSize * 100);tvname.setText(apkName + " 下载中...");tvprogress.setText(result + "%");pb.setProgress(Integer.parseInt(result));}}/*** 程序释放*/public void onDestroy() {super.onDestroy();if (task != null) {task.cancel(true);}Util.printLog(Tag, "onDestroy..isAppInstallByMobile:"+ BaseControl.isAppInstallByMobile);} }