您的位置:首页 > 移动开发 > Android开发

android版本检测更新的方法2

2016-07-19 17:56 465 查看
package com.ihmzone.app.mine;

import android.app.AlertDialog;

import android.app.Dialog;

import android.app.ProgressDialog;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.pm.PackageInfo;

import android.content.pm.PackageManager;

import android.database.sqlite.SQLiteDatabase;

import android.graphics.Bitmap;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.net.Uri;

import android.os.Bundle;

import android.os.Environment;

import android.os.Handler;

import android.os.Message;

import android.util.Log;

import android.view.View;

import android.widget.Button;

import android.widget.CompoundButton;

import android.widget.ImageView;

import android.widget.LinearLayout;

import android.widget.RelativeLayout;

import android.widget.TextView;

import android.widget.ToggleButton;

import com.bumptech.glide.Glide;

import com.bumptech.glide.load.engine.DiskCacheStrategy;

import com.easemob.chat.EMChatManager;

import com.ihmzone.app.R;

import com.ihmzone.app.activity.MainActivity;

import com.ihmzone.app.chat.activity.BasicParentActivity;

import com.ihmzone.app.chat.model.Login;

import com.ihmzone.app.chat.util.SharePreferenceUtil;

import com.ihmzone.app.foodshow.view.NikenameDialog;

import com.ihmzone.app.http.MineHttp;

import com.ihmzone.app.mine.dao.DBMineHelper;

import com.ihmzone.app.mine.dao.DBUtil;

import com.ihmzone.app.model.UserV0;

import com.ihmzone.app.user.activity.LoginActivity;

import com.ihmzone.app.utils.MyToast;

import com.ihmzone.app.view.CustomDialog;

import com.lidroid.xutils.BitmapUtils;

import com.luyun.arocklite.network.LYNetWorkUtils;

import com.luyun.arocklite.user.view.LYOnResponseDataListener;

import com.luyun.arocklite.utils.LYAppManager;

import com.luyun.arocklite.utils.LYLoadingDialog;

import com.luyun.arocklite.utils.LYStringUtil;

import com.luyun.arocklite.utils.LYToastUtil;

import com.luyun.arocklite.view.LYCustomToolbar;

import org.apache.http.conn.ssl.SSLSocketFactory;

import org.json.JSONObject;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.URL;

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

/**

* yuyue

*/

public class MineActivity extends BasicParentActivity {

private LYCustomToolbar toolbar;

private Button exit;

private LinearLayout ll_version, ll_about;

private RelativeLayout rl_set;

private ImageView headphoto;

private ImageView back_btn;

private ToggleButton tog_t, tog_s;

private TextView name;

private TextView phonenum;

private TextView line;

private Bundle bundle;

private Bitmap photo1;

private SQLiteDatabase db;

private DBUtil dba;

private MyToast toastCommom;

private BitmapUtils bitmapUtils;

private LYLoadingDialog dialog;
private Dialog dialog_app;//提示软件升级
private static final int ERROR = 1;//失败
private static final int NETWORK_ERROR = 2;//网络错误
private static final int SUCCESS = 3;//成功
private static final int LOGIN = 4;//登录
private static final int INSTALL_CODE = 5;//
private static final int DOWN_ERROR = 6;//
private static final int VERSION_SUCCESS = 7;//
private static final int VERSION_FAIL = 8;//

private String path;
private String serverVersion;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);

switch (msg.what) {
case ERROR:
LYToastUtil.showShortToast(MineActivity.this, "账号失效");


// goToLogin();

break;

case SUCCESS:

// startActivity(new Intent(LoadingActivity.this, MainActivity.class));

// finish();

break;

case NETWORK_ERROR:

break;
case LOGIN:


// login(name, pass);

break;

case VERSION_SUCCESS:

checkVersion();

break;

case VERSION_FAIL:

// doLogin();

break;

case DOWN_ERROR:

loadAppFail();

break;

}

}

};

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mine);
initView();
changebtn();
initDB();
if (Login.getuId() != null) {
setdata(
e70e
);
}
else{
name.setText("登录");
phonenum.setText("登录");
exit.setVisibility(View.GONE);
line.setVisibility(View.GONE);
}
}

@Override
protected void onResume() {
if (Login.getuId() != null) {
setdata();
}
super.onResume();
}

public void initView() {
exit = (Button) findViewById(R.id.exit);
ll_version = (LinearLayout) findViewById(R.id.ll__checkversion);
ll_about = (LinearLayout) findViewById(R.id.ll_aboutus);
rl_set = (RelativeLayout) findViewById(R.id.mine_set);
headphoto = (ImageView) findViewById(R.id.photo_set);
name = (TextView) findViewById(R.id.txt_photo);//昵称
phonenum = (TextView) findViewById(R.id.txt_phonenum);//电话
line = (TextView) findViewById(R.id.line);
back_btn = (ImageView)findViewById(R.id.iv_back);
toastCommom = MyToast.createToastConfig();

exit.setOnClickListener(onClickListener);
back_btn.setOnClickListener(onClickListener);
ll_version.setOnClickListener(onClickListener);
ll_about.setOnClickListener(onClickListener);
rl_set.setOnClickListener(onClickListener);
dialog = new LYLoadingDialog(MineActivity.this);
dialog.setTitle("版本检测中...");
}

View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
switch (view.getId()) {
case R.id.exit:
showdialog();
break;
case R.id.ll__checkversion://检测版本
if(LYNetWorkUtils.checkEnable(MineActivity.this)){
getAppVersion();
}else {
LYToastUtil.showShortToast(MineActivity.this,"网络没有连接,请先连接网络");
}
break;
case R.id.ll_aboutus:
intent.setClass(MineActivity.this, AboutUsActivity.class);
startActivity(intent);
break;
case R.id.mine_set:
if (Login.getuId() != null) {
phonenum.setVisibility(View.VISIBLE);
intent.putExtra("name",name.getText().toString());
intent.setClass(MineActivity.this, SetMyselfActivity.class);
startActivityForResult(intent, 1);
}
else {
login();
}
break;
case R.id.photo_set:
//从设置中提取
break;
case R.id.txt_photo:
//从设置中提取
break;
case R.id.txt_phonenum:
//从设置中提取
break;
case R.id.iv_back:
LYAppManager.getAppManager().finishLastActivity();
break;
}
}
};

/**
* 跳转登陆
*/
private void login() {
Intent intent = new Intent();
intent.setClass(MineActivity.this, LoginActivity.class);
intent.putExtra("login", "login");
startActivity(intent);
}

//获取最新版本
public void getAppVersion() {
dialog.show();
MineHttp.getAppVersion(MineActivity.this, new LYOnResponseDataListener() {
@Override
public void responseData(Object o) {
JSONObject response = (JSONObject) o;
try {
boolean result = response.getBoolean("success");
if (result) {
JSONObject data = response.getJSONObject("data");
JSONObject json = data.getJSONObject("versionVO");
String url_app = json.getString("url");
if (!LYStringUtil.isNULL(url_app)) {
path = url_app;
}

String ss = json.getString("versionNo");
serverVersion = ss;
Message msg = Message.obtain();
msg.what = VERSION_SUCCESS;
handler.sendMessage(msg);

} else {
Message msg = Message.obtain();
msg.what = VERSION_FAIL;
handler.sendMessage(msg);
}
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
public void onFailure(int i) {
Message msg = Message.obtain();
msg.what = VERSION_FAIL;
handler.sendMessage(msg);
dialog.dismiss();
}
});
}

//  切换按钮颜色,并设置
public void changebtn() {
tog_s = (ToggleButton) findViewById(R.id.tog_s);
tog_t = (ToggleButton) findViewById(R.id.tog_t);

boolean flag_t = SharePreferenceUtil.getGroupNotification(MineActivity.this, Login.getuId());
boolean flag_s = SharePreferenceUtil.getSystemNotification(MineActivity.this, Login.getuId());
tog_t.setChecked(flag_t);
tog_s.setChecked(flag_s);
tog_s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {


// LYToastUtil.showShortToast(MineActivity.this, “系统通知结果===” + b);

SharePreferenceUtil.putSystemNotification(MineActivity.this, Login.getuId(), b);

}

});

tog_t.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override

public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

// LYToastUtil.showShortToast(MineActivity.this,”结果===”+b);

SharePreferenceUtil.putGroupNotification(MineActivity.this, Login.getuId(), b);

}

});

}

// 注销对话框
private void showdialog() {
CustomDialog.Builder builder = new CustomDialog.Builder(MineActivity.this);
builder.setMessage("确定要退出登录吗");
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
MineHttp.getLogOutResult(MineActivity.this, new LYOnResponseDataListener() {
@Override
public void responseData(Object o) {
if (o != null) {
Log.d("fdsasdf", o + "");
Login.setPhone(null);
Login.setuId(null);
Login.setNickName(null);
Login.setPhotoUrl(null);
//退出环信服务器
EMChatManager.getInstance().logout();
String info = (String) o;


// LYToastUtil.showShortToast(MineActivity.this, info);

LYAppManager.getAppManager().finishAllActivity();

startActivity(new Intent(MineActivity.this, LoginActivity.class));

} else {

// LYToastUtil.showShortToast(MineActivity.this, “注销失败”);

}

}

@Override
public void onFailure(int i) {
if (i == 0) {
LYToastUtil.showShortToast(MineActivity.this, "网络出问题了,请稍后重试");
}
}
}
);
}
});
builder.create().show();
}

private void initDB() {
db = new DBMineHelper(this).getWritableDatabase();
dba = new DBUtil(db);
}

private void setdata() {//设置数据
UserV0 userV0 = new UserV0();
dba.querydata(userV0);
String nm = userV0.getNickName();
if(LYStringUtil.isNULL(nm)||nm.equals("未设置")){
name.setText(userV0.getPhoneNumber());
}else {
name.setText(nm);
}
phonenum.setVisibility(View.VISIBLE);
phonenum.setText(userV0.getPhoneNumber());
Glide.with(this).load(userV0.getUserPhoto()).error(R.drawable.head_icon).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(headphoto);
}

/**
* 获取本地版本
* @return
*/
public String getLocalVersion() {
String version = null;
try {
PackageInfo packageInfo = getApplicationContext()
.getPackageManager().getPackageInfo(getPackageName(), 0);
version = packageInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return version;
}

/**
* 提示更新
* @param title
*/
private void showDialog(String title) {
CustomDialog.Builder builder = new CustomDialog.Builder(MineActivity.this);
builder.setMessage(title);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
showNetWorkType();
dialogInterface.dismiss();
}
});
builder.create().show();
}
/**
* 检查是否更新版本
*/
public void checkVersion() {
String localVersion = getLocalVersion();
Log.i("UserHttpSendUtil", localVersion + "----" + serverVersion);
if (compareVersion(localVersion, serverVersion)) {
// 发现新版本,提示用户更新
showDialog("检查到新版本,是否更新?");
} else {
LYToastUtil.showShortToast(MineActivity.this, "已经在最新版本了");
}
}

/*
* 下载安装apk
* @param path
*
* */
private void showNetWorkType() {
if (isWifiActive(MineActivity.this)) {
loadApkFile(path);
} else {
dialog_app = new AlertDialog.Builder(MineActivity.this).setTitle("提示")
.setMessage("当前网络非wifi连接,会消耗手机流量,是否继续更新.")
.setCancelable(false)
.setPositiveButton("是",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
loadApkFile(path);
}
}).setNegativeButton("否", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {

}
}).create();
dialog_app.show();
}
}

public void loadApkFile(final String path) {
Log.i("LoginActivity", "path======" + path);
final ProgressDialog pd;    //进度条对话框
pd = new ProgressDialog(this);
pd.setCanceledOnTouchOutside(false);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下载更新");
pd.setProgressNumberFormat("%1d kb/%2d kb");
pd.show();
new Thread() {
@Override
public void run() {
try {
File file = getFileFromServer(path, pd);
installApk(file);
pd.dismiss(); //结束掉进度条对话框

} catch (Exception e) {
Log.i("LoginActivity", "Exception-------" + e.getMessage());
pd.dismiss();
Message msg = new Message();
msg.what = DOWN_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}.start();
}

//下载app失败
private void loadAppFail() {
AlertDialog dialog = new AlertDialog.Builder(MineActivity.this).setTitle("提示")
.setMessage("应用下载失败")
.setCancelable(false)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
}).create();
dialog.show();
}

/**
* 比较版本号
*/
public boolean compareVersion(String localVersion, String serverVersion) {
boolean necessity = false;
serverVersion = serverVersion.replace("v", "");
String[] versions = serverVersion.split("[.]");
String[] localversions = localVersion.split("[.]");
int len = versions.length > localversions.length ? localversions.length : versions.length;
for (int i = 0; i < len; i++) {
if (Integer.parseInt(versions[i]) > Integer.parseInt(localversions[i])) {
necessity = true;
break;
} else if (Integer.parseInt(versions[i]) < Integer.parseInt(localversions[i])) {
break;
} else if (i == len - 1
&& Integer.parseInt(versions[i]) == Integer.parseInt(localversions[i])
&& versions.length > localversions.length
&& Integer.parseInt(versions[versions.length - 1]) > 0) {
necessity = true;
break;
}
}
return necessity;
}

/*
* 下载apk任务
* @param path
* @param pd
* */
public File getFileFromServer(String path, ProgressDialog pd) throws Exception {
//如果相等的话表示当前的sdcard挂载在手机上并且是可用的
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
URL url = new URL(path);


// HttpURLConnection conn = (HttpURLConnection) url.openConnection();

HttpURLConnection conn = null;

trustAllHosts();

if (url.getProtocol().toLowerCase().equals(“https”)) {

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();

https.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

conn = https;

} else {

conn = (HttpURLConnection) url.openConnection();

}

conn.setConnectTimeout(5000);

//获取到文件的大小

int count = conn.getContentLength();

pd.setMax(count / 1024);

InputStream is = conn.getInputStream();

File file = new File(Environment.getExternalStorageDirectory(), “ahmzone.” + serverVersion + “.apk”);

FileOutputStream fos = new FileOutputStream(file);

BufferedInputStream bis = new BufferedInputStream(is);

byte[] buffer = new byte[1024];

int len;

int total = 0;

while ((len = bis.read(buffer)) != -1) {

fos.write(buffer, 0, len);

total += len;

//获取当前下载量

int i = (int) total / count;

pd.setProgress(total / 1024);

}

fos.close();

bis.close();

is.close();

return file;

} else {

return null;

}

}

/*
* 安装apk
* @param file
* */
public void installApk(File file) {
Intent intent = new Intent();
//执行动作
intent.setAction(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//执行的数据类型
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
//编者按:此处Android应为android,否则造成安装不了


// startActivityForResult(intent, INSTALL_CODE);

startActivity(intent);

finish();

}

// 判断当前是否使用的是 WIFI网络
public static boolean isWifiActive(Context icontext) {
Context context = icontext.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] info;
if (connectivity != null) {
info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getTypeName().equals("WIFI") && info[i].isConnected()) {
return true;
}
}
}
}
return false;
}

private static void trustAllHosts() {
final String TAG = "trustAllHosts";
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}

public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i(TAG, "checkClientTrusted");
}

public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
Log.i(TAG, "checkServerTrusted");
}
}};

// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) ;
if (requestCode == 1) {
setdata();
}

}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: