关于Android 版本更新
来源:互联网 发布:linux 安装ftp 编辑:程序博客网 时间:2024/06/04 20:09
版本更新是个老话题了,第三方框架也有许多,在这里就不多做介绍了,给大家来点干货方便大家学习。本本主要是依据后台提供的
versionCode和本地的versionCode进行比较,包含了强制升级和非强制升级两种废话不多说直接上干货了:
首先需要申明变量
private String BANBENHAO = "";//被忽略的版本号private boolean isFirst;//判断发现新版本后是否是第一次弹出升级框在数据获取成功后进行调用方法
public void dataOkIsUpgrade(){final String versionCode = bean.versionCode;//从网上获取的版本号String downLoadUrl = "";//下载地址if (bean != null && bean.downLoadUrl != null) { downLoadUrl = bean.downLoadUrl;}final String mFinalDownloadUrl = downLoadUrl;double serviceCode = Double.parseDouble(versionCode);//double code = TDevice.getVersionCode();TDevice.getVersionCode()是获取本地versionCode的方法
//从网上获取是否需强制升级 1 代表强制升级,0 代表非强制升级
String isForceUpdate = "";
if (!bean.isForce.equals("")) {isForceUpdate = bean.isForce;
}//从网上获取的更新信息内容
String updateInfo = "";
if (!bean.updateInfo.equals("")) {updateInfo = bean.updateInfo;
}final String updateDes = updateInfo;
//保存从网上获取的serviceCodeSPHelper.getInst().saveString("serviceCode", versionCode);//判断是否忽略过版本 SPHelper是一个SharedPreferences的工具类为了方便使用
BANBENHAO = SPHelper.getInst().getString("BANBENHAO");if (!BANBENHAO.equals("")) {double SERVICECD = Double.parseDouble(BANBENHAO);if (SERVICECD < serviceCode) {
isFirst = true;} else {
isFirst = false;}SPHelper.getInst().saveBoolean("isFirst", isFirst);} else {
isFirst = true;BANBENHAO = versionCode;
SPHelper.getInst().saveBoolean("isFirst", isFirst);}//判断发现新版本后是否是第一次弹出升级框
isFirst = SPHelper.getInst().getBoolean("isFirst");//判断是否需要版本升级
if (code != serviceCode && code < serviceCode) {
SPHelper.getInst().saveString("downLoadUrl", downLoadUrl);if (isFirst || isForceUpdate.equals("1")) {selfDialog = new SelfDialog(getContext(), R.style.dialog, updateDes);selfDialog.show();
selfDialog.setYesOnclickListener("立即升级", new SelfDialog.onYesOnclickListener() {@Overridepublic void onYesClick() {new UpdateManager(getContext(), _mActivity, mFinalDownloadUrl);selfDialog.dismiss();
}});//若强制升级显示if (isForceUpdate.equals("1")) {selfDialog.setNoOnclickListener("退出", new SelfDialog.onNoOnclickListener() {@Overridepublic void onNoClick() {selfDialog.dismiss();
getActivity().finish();}});} else if (isForceUpdate.equals("0")) {//若非强制升级时显示selfDialog.setNoOnclickListener("忽略此次", new SelfDialog.onNoOnclickListener() {@Overridepublic void onNoClick() {isFirst = false;SPHelper.getInst().saveBoolean("isFirst", isFirst);//保存到本地BANBENHAO = versionCode;SPHelper.getInst().saveString("updateDes", updateDes);SPHelper.getInst().saveString("BANBENHAO", BANBENHAO);selfDialog.dismiss();
}});}}}}
下面给大家来一个上面用到的自定义的dialogSelfDialog//自定义dialogpublic class SelfDialog extends Dialog { //确定文本和取消文本的显示内容 private String yesStr, noStr; private onNoOnclickListener noOnclickListener;//取消按钮被点击了的监听器 private onYesOnclickListener yesOnclickListener;//确定按钮被点击了的监听器 private TextView selfMSG; private Button yes, no; private String versonMSG; public SelfDialog(Context context) { super(context); } public SelfDialog(Context context, int themeResId) { super(context, themeResId); } public SelfDialog(Context context, int themeResId ,String versonMSG) { super(context, themeResId); this.versonMSG=versonMSG; } /** * 设置取消按钮的显示内容和监听 * * @param str * @param onNoOnclickListener */ public void setNoOnclickListener(String str, onNoOnclickListener onNoOnclickListener) { no.setText(str); if (str != null) { noStr = str; } this.noOnclickListener = onNoOnclickListener; } /** * 设置确定按钮的显示内容和监听 * * @param str * @param onYesOnclickListener */ public void setYesOnclickListener(String str, onYesOnclickListener onYesOnclickListener) { yes.setText(str); if (str != null) { yesStr = str; } this.yesOnclickListener = onYesOnclickListener; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.selfdialog); initView(); setCancelable(false); //初始化界面控件的事件 initEvent(); } private void initEvent() { //设置确定按钮被点击后,向外界提供监听 yes.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (yesOnclickListener != null) { yesOnclickListener.onYesClick(); } } }); //设置取消按钮被点击后,向外界提供监听 no.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (noOnclickListener != null) { noOnclickListener.onNoClick(); } } }); } private void initView() { selfMSG = ((TextView) findViewById(R.id.selfdg_mesg)); yes = (Button) findViewById(R.id.selfdg_yes); no = (Button) findViewById(R.id.selfdg_no); selfMSG.setText(versonMSG); } /** * 设置确定按钮和取消被点击的接口 */ public interface onYesOnclickListener { public void onYesClick(); } public interface onNoOnclickListener { public void onNoClick(); }}SelfDialog的布局<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical"> <LinearLayout android:layout_width="250dp" android:layout_height="wrap_content" android:layout_marginLeft="27dip" android:layout_marginRight="27dip" android:background="@drawable/shape_dialog" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="18dip" android:text="发现新版本请更新" android:textColor="@color/Title_color" android:textSize="20sp" /> <TextView android:id="@+id/selfdg_mesg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="26dp" android:layout_marginRight="20dp" android:layout_marginTop="18dip" android:text="避免影响使用及时请更新" android:textSize="14sp" /> <LinearLayout android:layout_width="210dp" android:layout_height="33dp" android:layout_gravity="center|bottom" android:layout_marginBottom="20dp" android:layout_marginTop="23dp"> <Button android:id="@+id/selfdg_yes" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/shape_bottom" android:text="确定" android:paddingLeft="15dp" android:paddingRight="15dp" android:textColor="@color/white" android:textSize="16sp" /> <View android:layout_width="15dp" android:layout_height="match_parent" /> <Button android:id="@+id/selfdg_no" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:background="@drawable/shap_gray_bottom" android:text="取消" android:paddingLeft="15dp" android:paddingRight="15dp" android:textColor="@color/white" android:textSize="16sp" /> </LinearLayout> </LinearLayout></LinearLayout>上面还用到了一个style其实很简单为了方便就一遍给大家了<style name="dialog" parent="@android:style/Theme.Dialog"> <item name="android:windowFrame">@null</item> <item name="android:windowIsFloating">true</item> <item name="android:windowIsTranslucent">false</item> <item name="android:windowNoTitle">true</item> <item name="android:windowBackground">@android:color/transparent</item> <item name="android:backgroundDimEnabled">true</item></style>再下来就是下载的工具了 下载完成后会弹出安装页面哦再来就是下载进度条的布局很简单的public class UpdateManager { /* 下载中 */ private static final int DOWNLOAD = 1; /* 下载结束 */ private static final int DOWNLOAD_FINISH = 2; /* 下载保存路径 */ private String mSavePath; /* 记录进度条数量 */ private int progress; /* 是否取消更新 */ private boolean cancelUpdate = false; private Activity activity; private Context mContext; /* 更新进度条 */ private ProgressBar mProgress; private TextView tv; private Dialog mDownloadDialog; /** * 下载链接 */ private String path = ""; /*文件名*/ private String name = ""; private Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { // 正在下载 case DOWNLOAD: // 设置进度条位置 mProgress.setProgress(progress); tv.setText("已完成 : " + progress + "%"); break; case DOWNLOAD_FINISH: // 安装文件 installApk(); break; default: break; } } ; }; public UpdateManager(Context context, Activity activity ,String downLoadUrl) { this.mContext = context; this.activity = activity; this.path = downLoadUrl; if(!downLoadUrl.equals("")) { this.name = path.substring(path.lastIndexOf("/") + 1); } showDownloadDialog(); } /** * 下载对话框 */ private void showDownloadDialog() { // 构造软件下载对话框 mDownloadDialog = new Dialog(mContext, R.style.dialog); Builder builder = new Builder(mContext); // 给下载对话框增加进度条 final LayoutInflater inflater = LayoutInflater.from(mContext); View v = inflater.inflate(R.layout.softupdate_progress, null); mProgress = (ProgressBar) v.findViewById(R.id.update_progress); tv = (TextView) v.findViewById(R.id.xiazaijindu); builder.setView(v);// // 取消更新// builder.setNegativeButton("取消", new OnClickListener() {// @Override// public void onClick(DialogInterface dialog, int which) {// dialog.dismiss();// // 设置取消状态// cancelUpdate = true;// }// }); mDownloadDialog = builder.create(); mDownloadDialog.setCancelable(false); mDownloadDialog.show(); // 现在文件 if(!path.equals("")) { downloadApk(); } } /** * 下载apk文件 */ private void downloadApk() { // 启动新线程下载软件 new downloadApkThread().start(); } /** * 下载文件线程 */ private class downloadApkThread extends Thread { @Override public void run() { try { // 判断SD卡是否存在,并且是否具有读写权限 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 获得存储卡的路径 String sdpath = Environment.getExternalStorageDirectory() + "/"; mSavePath = sdpath + "download"; URL url = new URL(path); // 创建连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.connect(); // 获取文件大小 int length = conn.getContentLength(); // 创建输入流 InputStream is = conn.getInputStream(); File file = new File(mSavePath); // 判断文件目录是否存在 if (!file.exists()) { file.mkdir(); } File apkFile = new File(mSavePath, name); FileOutputStream fos = new FileOutputStream(apkFile); int count = 0; // 缓存 byte buf[] = new byte[1024]; // 写入到文件中 do { int numread = is.read(buf); count += numread; // 计算进度条位置 progress = (int) (((float) count / length) * 100); // 更新进度 mHandler.sendEmptyMessage(DOWNLOAD); if (numread <= 0) { // 下载完成 mHandler.sendEmptyMessage(DOWNLOAD_FINISH); break; } // 写入文件 fos.write(buf, 0, numread); } while (!cancelUpdate);// 点击取消就停止下载. fos.close(); is.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 取消下载对话框显示 mDownloadDialog.dismiss(); } } ; /** * 安装APK文件 */ private void installApk() { File apkfile = new File(mSavePath, name); if (!apkfile.exists()) { return; } // 通过Intent安装APK文件 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(apkfile), "application/vnd.android.package-archive"); mContext.startActivity(intent); activity.finish(); }}<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/shape_dialog" android:orientation="vertical"> <TextView android:layout_marginTop="20dp" android:gravity="center" android:layout_marginLeft="27dip" android:layout_marginRight="27dip" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="正在下载" /> <ProgressBar android:layout_marginLeft="27dip" android:layout_marginRight="27dip" android:id="@+id/update_progress" android:layout_marginTop="20dip" style="?android:attr/progressBarStyleHorizontal" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:gravity="center" android:layout_marginLeft="27dip" android:layout_marginRight="27dip" android:id="@+id/xiazaijindu" android:layout_marginTop="20dip" android:layout_marginBottom="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="0%" /> </LinearLayout></LinearLayout>好了上面这些完成就可以在首页加载数据是弹出升级提示框,具体的那些drawable文件都是些自定义的就不给大家了
如果在设置里有检查版本的话可以添加下面的代码
//获取当前网络版本号private double getServiceCode() { double serviceCode = Double.parseDouble(getInst().getString("serviceCode")); return serviceCode;}//判断是否需要升级private boolean isUpdate() { if (versionCode != getServiceCode() && versionCode< getServiceCode()) { String URL = getInst().getString("downLoadUrl"); if (!URL.equals("")) { final String mDownLoadUrl = URL; String updateDes = SPHelper.getInst().getString("updateDes"); selfDialog = new SelfDialog(getContext(), R.style.dialog, updateDes); selfDialog.show(); selfDialog.setYesOnclickListener("立即升级", new SelfDialog.onYesOnclickListener() { @Override public void onYesClick() { new UpdateManager(getContext(), _mActivity, mDownLoadUrl); selfDialog.dismiss(); } }); selfDialog.setNoOnclickListener("取消", new SelfDialog.onNoOnclickListener() { @Override public void onNoClick() { selfDialog.dismiss(); } }); return true; } return false; } else { Toast.makeText(getContext(), "已是最新版本无需更新", Toast.LENGTH_LONG).show(); return false; }}点击检查更新的按钮执行isUpdate()方法就好了,至于检查更新是否有提示可以根据//获取是否忽略过版本更新String banben = SPHelper.getInst().getString("BANBENHAO");来判断。好了如果本文对您有帮助记得点个赞哦,谢谢!!
阅读全文
0 0
- 关于Android 版本更新
- android关于版本更新问题
- Android关于apk版本更新方法
- android关于版本更新问题二
- 友盟更新 — 关于android 版本更新
- Android——关于android应用如何更新版本?
- 关于版本更新
- Android中关于APP的版本更新问题
- Android版本更新
- Android SDK版本更新
- Android软件版本更新
- Android 检测版本更新
- Android之版本更新
- Android版本更新实现
- android版本更新问题
- android apk版本更新
- android版本更新
- Android 版本的更新
- 心灵之火的瞬间-第二则
- minicom使用
- 初级-文件操作与字符处理
- Throwable和Exception的区别
- python读取并处理CSV文件
- 关于Android 版本更新
- 读写锁SRWLock
- 朋友圈
- Java中关键字static的作用
- 《数字技术》连载6: 第2章 数字器件 第1节 基本门电路
- mybatis详解-(5)面向接口
- 《OurwayBI基础入门系列--学会数据快速可视化》开课啦 !
- Mysql分库分表方案
- oracle--14.pl,sql语言