private static final String TAG = "AutoUpdateActivty";
private Context context = AutoUpdateActivty.this;
private Activity activity = AutoUpdateActivty.this;
private TextView percentTextView;
private SharedPreferences sp = null;
private ProgressDialog pBar;
private ProgressBar pt_checkupdate_pro;
private String apkDownPathDir = "";
private String versionJson = ConstantUtil.HTTP_APK_JSON;
private String apkName = ConstantUtil.HTTP_APK_Name;
private String newVersionName = "";
private int newVersionCode = -1;
private int apkSize;
private int downLoadApkSize;
private String json = null;
private GetJsonTask jsonTask = null;
private boolean debugMode=true; //设置环境模式
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 0x111:
Intent in = new Intent();
in.setClass(activity,MainActivity.class);
activity.startActivity(in);
AutoUpdateActivty.this.finish();
break;
case 0x112:
long result = downLoadApkSize * 100 / apkSize;
pBar.show();
pBar.setMessage("请稍后..." + result + "%");
percentTextView.setText("应用升级检测..." + result + "%");
break;
case 0x999:
if(null!=pt_checkupdate_pro && pt_checkupdate_pro.isShown())
{
pt_checkupdate_pro.cancelLongPress();
}
Toast.makeText(context, "APK升级网络不通", Toast.LENGTH_LONG).show();
percentTextView.setText("APK升级网络不通");
percentTextView.setTextColor(Color.RED);
break;
case 1001:
;
break;
case 1002:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
setRequestedOrientation(PTSDKCmd.ORIENTATION);
percentTextView = (TextView) findViewById(R.id.percentTextView);
apkDownPathDir = getString(R.string.updateUrl).trim();
pt_checkupdate_pro=(ProgressBar) findViewById(R.id.pt_checkupdate_pro);
jsonTask = new GetJsonTask();
jsonTask.execute(apkDownPathDir + versionJson);
}
private class GetJsonTask extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
json = HttpServletTool.getPostDataByServlet(params[0], null);
LogUtil.i(TAG, "json: " + json);
if (!"".equals(json) && null != json)
{
try
{
//{"ptapp":{"versionCode":"2","versionName":"1.0.1"}}
JSONObject jsonobj=new JSONObject(json).getJSONObject("ptapp");
newVersionCode = Integer.parseInt(jsonobj.optString("versionCode","0"));
newVersionName = jsonobj.getString("versionName");
} catch (Exception e)
{
newVersionCode = -1;
LogUtil.e(TAG, e.getMessage());
}
} else
{
newVersionCode = -1;
}
return String.valueOf(newVersionCode);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
int currVerCode = ApkVersionTool.getVerCode(context);
LogUtil.i(TAG, "currVCode:" + currVerCode + " ;newVCode:" + newVersionCode + " ;newVName:" + newVersionName);
if (newVersionCode > currVerCode)
{
showUpdateDialog();
} else
{
sendMsg(0x111);
}
}
}
/** 显示是否更新对话框**/
private void showUpdateDialog()
{
StringBuffer sb = new StringBuffer();
//sb.append("当前版本代码:");
//sb.append(ApkVersionTool.getVerCode(context) + "; ");
sb.append("检测版本信息:\n");
sb.append("当前版本:");
sb.append(ApkVersionTool.getVerName(context));
sb.append("\n");
//sb.append("最新版本代码:");
//sb.append(newVersionCode + "; ");
sb.append("最新版本:");
sb.append(newVersionName);
sb.append("\n");
sb.append("是否更新?");
Dialog dialog = new AlertDialog.Builder(context)
.setTitle("软件更新")//
.setMessage(sb.toString())
.setPositiveButton("更新",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
showUpdateProgressDialog();
}
})
.setNegativeButton("暂不更新", //
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
sendMsg(0x111);
}
}).create();
dialog.setCancelable(false);
dialog.show();
}
/** 更新当前版本 **/
private void showUpdateProgressDialog()
{
pBar = new ProgressDialog(context);
pBar.setTitle("正在下载");
pBar.setMessage("请稍后");
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pBar.setCanceledOnTouchOutside(false);
pBar.setCancelable(true);
downloadApK(apkDownPathDir + apkName);
}
/** 下载APK **/
private void downloadApK(final String apkUrl)
{
LogUtil.i(TAG, "Apk Url:" + apkUrl);
pBar.show();
new Thread()
{
@Override
public void run()
{
HttpGet get = new HttpGet(apkUrl);
HttpResponse response;
try
{
response = HttpClientTool.getHttpClient().execute(get);
HttpEntity entity = response.getEntity();
apkSize = (int) entity.getContentLength();// 根据响应获取文件大小
LogUtil.i(TAG, "Down Apk length:" + apkSize);
InputStream inStream = entity.getContent();
FileOutputStream outStream = null;
if (null == inStream)
{
LogUtil.e(TAG, "Apk Stream is null");
throw new RuntimeException("isStream is null");
}
File file = new File(Environment.getExternalStorageDirectory(), apkName);
outStream = new FileOutputStream(file);
byte[] buf = new byte[8192];
int len = -1;
do
{
len = inStream.read(buf);
LogUtil.i("len", ">> " + len);
if (-1 == len) {
LogUtil.i(TAG, "Apk downLoading Size2 >>:" + downLoadApkSize);
if (downLoadApkSize < apkSize)
{
response = HttpClientTool.getHttpClient().execute(get);
Thread.sleep(1000);
if (null == response)
{
LogUtil.e("response", "response null");
sendMsg(0x999);
}
entity = response.getEntity();
inStream = entity.getContent();
inStream.mark(downLoadApkSize);
} else
{
LogUtil.i(TAG, "[downLoadApkSize = apkSize]" + apkSize);
break;
}
}
outStream.write(buf, 0, len);
downLoadApkSize += len;
LogUtil.i(TAG, "Apk downLoading Size1:" + downLoadApkSize);
// 更新进度
sendMsg(0x112);
} while (true);
inStream.close();
outStream.close();
// 更新完毕
downLoadApkOver();
} catch (Exception e)
{
LogUtil.e(TAG, e.getMessage());
}
}
}.start();
}
/** 下载完毕后,取消进度框,准备安装APK **/
private void downLoadApkOver()
{
LogUtil.i(TAG, "APK下载完毕");
handler.post(new Runnable()
{
public void run()
{
pBar.cancel();
// 弹出对话框是否安装下载的APK
Dialog installDialog = new AlertDialog.Builder(context)
.setTitle("下载完成")//
.setMessage("是否安装新的应用")//
.setPositiveButton("确定", //
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
installNewApk();
finish();
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
sendMsg(0x111);
}
}).create();
installDialog.show();
}
});
}
/** 安装下载的APK **/
private void installNewApk()
{
//ToolUtil.openfile(apkName, context);
File file = new File(Environment.getExternalStorageDirectory(), apkName);
if(!file.exists())return;
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}
/** 发消息 **/
private void sendMsg(int number)
{
Message msg = new Message();
msg.what = number;
handler.sendMessage(msg);
}
private Context context = AutoUpdateActivty.this;
private Activity activity = AutoUpdateActivty.this;
private TextView percentTextView;
private SharedPreferences sp = null;
private ProgressDialog pBar;
private ProgressBar pt_checkupdate_pro;
private String apkDownPathDir = "";
private String versionJson = ConstantUtil.HTTP_APK_JSON;
private String apkName = ConstantUtil.HTTP_APK_Name;
private String newVersionName = "";
private int newVersionCode = -1;
private int apkSize;
private int downLoadApkSize;
private String json = null;
private GetJsonTask jsonTask = null;
private boolean debugMode=true; //设置环境模式
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 0x111:
Intent in = new Intent();
in.setClass(activity,MainActivity.class);
activity.startActivity(in);
AutoUpdateActivty.this.finish();
break;
case 0x112:
long result = downLoadApkSize * 100 / apkSize;
pBar.show();
pBar.setMessage("请稍后..." + result + "%");
percentTextView.setText("应用升级检测..." + result + "%");
break;
case 0x999:
if(null!=pt_checkupdate_pro && pt_checkupdate_pro.isShown())
{
pt_checkupdate_pro.cancelLongPress();
}
Toast.makeText(context, "APK升级网络不通", Toast.LENGTH_LONG).show();
percentTextView.setText("APK升级网络不通");
percentTextView.setTextColor(Color.RED);
break;
case 1001:
;
break;
case 1002:
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.update);
setRequestedOrientation(PTSDKCmd.ORIENTATION);
percentTextView = (TextView) findViewById(R.id.percentTextView);
apkDownPathDir = getString(R.string.updateUrl).trim();
pt_checkupdate_pro=(ProgressBar) findViewById(R.id.pt_checkupdate_pro);
jsonTask = new GetJsonTask();
jsonTask.execute(apkDownPathDir + versionJson);
}
private class GetJsonTask extends AsyncTask<String, String, String>
{
@Override
protected String doInBackground(String... params)
{
json = HttpServletTool.getPostDataByServlet(params[0], null);
LogUtil.i(TAG, "json: " + json);
if (!"".equals(json) && null != json)
{
try
{
//{"ptapp":{"versionCode":"2","versionName":"1.0.1"}}
JSONObject jsonobj=new JSONObject(json).getJSONObject("ptapp");
newVersionCode = Integer.parseInt(jsonobj.optString("versionCode","0"));
newVersionName = jsonobj.getString("versionName");
} catch (Exception e)
{
newVersionCode = -1;
LogUtil.e(TAG, e.getMessage());
}
} else
{
newVersionCode = -1;
}
return String.valueOf(newVersionCode);
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
int currVerCode = ApkVersionTool.getVerCode(context);
LogUtil.i(TAG, "currVCode:" + currVerCode + " ;newVCode:" + newVersionCode + " ;newVName:" + newVersionName);
if (newVersionCode > currVerCode)
{
showUpdateDialog();
} else
{
sendMsg(0x111);
}
}
}
/** 显示是否更新对话框**/
private void showUpdateDialog()
{
StringBuffer sb = new StringBuffer();
//sb.append("当前版本代码:");
//sb.append(ApkVersionTool.getVerCode(context) + "; ");
sb.append("检测版本信息:\n");
sb.append("当前版本:");
sb.append(ApkVersionTool.getVerName(context));
sb.append("\n");
//sb.append("最新版本代码:");
//sb.append(newVersionCode + "; ");
sb.append("最新版本:");
sb.append(newVersionName);
sb.append("\n");
sb.append("是否更新?");
Dialog dialog = new AlertDialog.Builder(context)
.setTitle("软件更新")//
.setMessage(sb.toString())
.setPositiveButton("更新",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
showUpdateProgressDialog();
}
})
.setNegativeButton("暂不更新", //
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
sendMsg(0x111);
}
}).create();
dialog.setCancelable(false);
dialog.show();
}
/** 更新当前版本 **/
private void showUpdateProgressDialog()
{
pBar = new ProgressDialog(context);
pBar.setTitle("正在下载");
pBar.setMessage("请稍后");
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pBar.setCanceledOnTouchOutside(false);
pBar.setCancelable(true);
downloadApK(apkDownPathDir + apkName);
}
/** 下载APK **/
private void downloadApK(final String apkUrl)
{
LogUtil.i(TAG, "Apk Url:" + apkUrl);
pBar.show();
new Thread()
{
@Override
public void run()
{
HttpGet get = new HttpGet(apkUrl);
HttpResponse response;
try
{
response = HttpClientTool.getHttpClient().execute(get);
HttpEntity entity = response.getEntity();
apkSize = (int) entity.getContentLength();// 根据响应获取文件大小
LogUtil.i(TAG, "Down Apk length:" + apkSize);
InputStream inStream = entity.getContent();
FileOutputStream outStream = null;
if (null == inStream)
{
LogUtil.e(TAG, "Apk Stream is null");
throw new RuntimeException("isStream is null");
}
File file = new File(Environment.getExternalStorageDirectory(), apkName);
outStream = new FileOutputStream(file);
byte[] buf = new byte[8192];
int len = -1;
do
{
len = inStream.read(buf);
LogUtil.i("len", ">> " + len);
if (-1 == len) {
LogUtil.i(TAG, "Apk downLoading Size2 >>:" + downLoadApkSize);
if (downLoadApkSize < apkSize)
{
response = HttpClientTool.getHttpClient().execute(get);
Thread.sleep(1000);
if (null == response)
{
LogUtil.e("response", "response null");
sendMsg(0x999);
}
entity = response.getEntity();
inStream = entity.getContent();
inStream.mark(downLoadApkSize);
} else
{
LogUtil.i(TAG, "[downLoadApkSize = apkSize]" + apkSize);
break;
}
}
outStream.write(buf, 0, len);
downLoadApkSize += len;
LogUtil.i(TAG, "Apk downLoading Size1:" + downLoadApkSize);
// 更新进度
sendMsg(0x112);
} while (true);
inStream.close();
outStream.close();
// 更新完毕
downLoadApkOver();
} catch (Exception e)
{
LogUtil.e(TAG, e.getMessage());
}
}
}.start();
}
/** 下载完毕后,取消进度框,准备安装APK **/
private void downLoadApkOver()
{
LogUtil.i(TAG, "APK下载完毕");
handler.post(new Runnable()
{
public void run()
{
pBar.cancel();
// 弹出对话框是否安装下载的APK
Dialog installDialog = new AlertDialog.Builder(context)
.setTitle("下载完成")//
.setMessage("是否安装新的应用")//
.setPositiveButton("确定", //
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
installNewApk();
finish();
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
sendMsg(0x111);
}
}).create();
installDialog.show();
}
});
}
/** 安装下载的APK **/
private void installNewApk()
{
//ToolUtil.openfile(apkName, context);
File file = new File(Environment.getExternalStorageDirectory(), apkName);
if(!file.exists())return;
Uri uri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setDataAndType(uri, "application/vnd.android.package-archive");
context.startActivity(intent);
}
/** 发消息 **/
private void sendMsg(int number)
{
Message msg = new Message();
msg.what = number;
handler.sendMessage(msg);
}