30、Splash 开启软件就连接服务器检查是否需要升级

——————————–main.java—————————

package com.example.splash;import java.io.File;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import net.tsz.afinal.FinalHttp;import net.tsz.afinal.http.AjaxCallBack;import org.json.JSONException;import org.json.JSONObject;import android.app.AlertDialog;import android.app.AlertDialog.Builder;import android.content.DialogInterface;import android.content.DialogInterface.OnCancelListener;import android.content.DialogInterface.OnClickListener;import android.content.Intent;import android.content.SharedPreferences;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.content.pm.PackageManager.NameNotFoundException;import android.net.Uri;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.support.v7.app.ActionBarActivity;import android.view.View;import android.view.animation.AlphaAnimation;import android.widget.TextView;import android.widget.Toast;public class MainActivity extends ActionBarActivity {protected static final int SHOW_UPDATE_DIALOG = 0;protected static final int ENTER_HOME = 1;protected static final int URL_ERROR = 2;protected static final int NETWORK_ERROR = 3;protected static final int JSON_ERROR = 4;private TextView tv_splash_version;private String description;private TextView tv_update_info;/*** 新版本的下载地址*/private String apkurl;private SharedPreferences sp;//判斷是否進入首頁private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// TODO Auto-generated method stubsuper.handleMessage(msg);switch (msg.what) {case SHOW_UPDATE_DIALOG:// 显示升级的对话框showUpdateDialog();break;case ENTER_HOME:// 进入主页面enterHome();break;case URL_ERROR:// URL错误enterHome();Toast.makeText(getApplicationContext(), "URL错误", 0).show();break;case NETWORK_ERROR:// 网络异常enterHome();Toast.makeText(MainActivity.this, "网络异常", 0).show();break;case JSON_ERROR:// JSON解析出错enterHome();Toast.makeText(MainActivity.this, "JSON解析出错", 0).show();break;default:break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);sp = getSharedPreferences("config", MODE_PRIVATE);tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);tv_splash_version.setText("版本号" + getVersionName());tv_update_info = (TextView) findViewById(R.id.tv_update_info);boolean update = sp.getBoolean("update", false); //if你想测试,就把false改为trueif(update){// 检查升级checkUpdate();}else{//自动升级已经关闭handler.postDelayed(new Runnable() {@Overridepublic void run() {//进入主页面enterHome();}}, 2000);}AlphaAnimation aa = new AlphaAnimation(0.2f, 1.0f);aa.setDuration(500);findViewById(R.id.rl_root_splash).startAnimation(aa);}

/*** 得到应用程序的版本名称*/private String getVersionName() {// 用来管理手机的APKPackageManager pm = getPackageManager();try {// 得到知道APK的功能清单文件PackageInfo info = pm.getPackageInfo(getPackageName(), 0);return info.versionName;} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();return "";}}/*** 检查是否有新版本,如果有就升级*/private void checkUpdate() {new Thread() {public void run() {// URL:8080/updateinfo.htmlMessage mes = Message.obtain();long startTime = System.currentTimeMillis();try {//連接服務器看是否需要更新URL url = new URL(":8080/NewsServer/updateinfo.json");// 联网HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(4000);int code = conn.getResponseCode();if (code == 200) {// 联网成功InputStream is = conn.getInputStream();// 把流转成StringString result = StreamTools.readFromStream(is);// json解析JSONObject obj = new JSONObject(result);// 得到服务器的版本信息String version = (String) obj.get("version");description = (String) obj.get("description");apkurl = (String) obj.get("apkurl");// 校验是否有新版本if (getVersionName().equals(version)) {// 版本一致,没有新版本,,进入主页面mes.what = ENTER_HOME;} else {// 有新版本,弹出一升级对话框mes.what = SHOW_UPDATE_DIALOG;}}} catch (MalformedURLException e) {// TODO Auto-generated catch blockmes.what = URL_ERROR;e.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blockmes.what = NETWORK_ERROR;e.printStackTrace();} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();mes.what = JSON_ERROR;} finally {long endTime = System.currentTimeMillis();// 我们花了多少时间long dTime = endTime – startTime;// 2000if (dTime < 2000) {try {Thread.sleep(2000 – dTime);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}handler.sendMessage(mes);}};}.start();}/*** 弹出升级对话框*/protected void showUpdateDialog() {//this = Activity.thisAlertDialog.Builder builder = new Builder(MainActivity.this);builder.setTitle("提示升级");//builder.setCancelable(false);//强制升级builder.setOnCancelListener(new OnCancelListener() {@Overridepublic void onCancel(DialogInterface dialog) {// TODO Auto-generated method stub//进入主页面enterHome();dialog.dismiss();}});builder.setMessage(description);builder.setPositiveButton("立刻升级", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// 下载APK,并且替换安装if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {// sdcard存在// afnalFinalHttp finalhttp = new FinalHttp();finalhttp.download(apkurl, Environment.getExternalStorageDirectory().getAbsolutePath()+"/mobilesafe2.0.apk",new AjaxCallBack<File>() {@Overridepublic void onFailure(Throwable t, int errorNo,String strMsg) {t.printStackTrace();Toast.makeText(getApplicationContext(), "下载失败", 1).show();super.onFailure(t, errorNo, strMsg);}@Overridepublic void onLoading(long count, long current) {// TODO Auto-generated method stubsuper.onLoading(count, current);tv_update_info.setVisibility(View.VISIBLE);//当前下载百分比int progress = (int) (current * 100 / count);tv_update_info.setText("下载进度:"+progress+"%");}@Overridepublic void onSuccess(File t) {// TODO Auto-generated method stubsuper.onSuccess(t);installAPK(t);}/*** 安装APK* @param t*/private void installAPK(File t) {Intent intent = new Intent();intent.setAction("android.intent.action.VIEW");intent.addCategory("android.intent.category.DEFAULT");intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive");startActivity(intent);}});} else {Toast.makeText(getApplicationContext(), "没有sdcard,请安装上在试",0).show();return;}}});builder.setNegativeButton("下次再说", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog.dismiss();enterHome();// 进入主页面}});builder.show();}protected void enterHome() {Intent intent = new Intent(this, HomeActivity.class);startActivity(intent);// 关闭当前页面finish();}}

—————————-StreamTools.java————把输入流转换为字符串———–

画龙画虎难画骨,知人知面不知心。

30、Splash 开启软件就连接服务器检查是否需要升级

相关文章:

你感兴趣的文章:

标签云: