android 自动更新APP版本,并使用ProgressDialog显示进度
来源:互联网 发布:淘宝卖家衣服轮播图 编辑:程序博客网 时间:2024/06/06 13:15
一、主要应用异步消息处理机制,在子线程进行版本检测和版本对比,如有新版本则开启新的线程去下载,并在progressDialog上显示下载进度,最后自动安装,这就是大概的实现思路。主要用到的知识就是网络请求和异步消息处理,以及文件读写。
二、代码如下
1、主活动
private UpdateAppManager manager;protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.guide); manager=new UpdateAppManager(this); manager.getUpdateMsg();//检查更新
2、更新管理类
public class UpdateAppManager { // 外存sdcard存放路径 private static final String FILE_PATH = Environment.getExternalStorageDirectory() +"/" + "AutoUpdate" +"/"; // 下载应用存放全路径 private static final String FILE_NAME = FILE_PATH + "AutoUpdate.apk"; // 准备安装新版本应用标记 private static final int INSTALL_TOKEN = 1; //Log日志打印标签 private static final String TAG = "Update_log"; private Context context; //获取版本数据的地址 private String version_path = "http://10.3.3.239/get_data.json"; //获取新版APK的默认地址 private String apk_path = "http://10.3.3.239/PLAYBULBX.apk"; // 下载应用的进度条 private ProgressDialog progressDialog; //新版本号和描述语言 private int update_versionCode; private String update_describe; public UpdateAppManager(Context context) { this.context = context; } /** * 获取当前版本号 */ private int getCurrentVersion() { try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); Log.e(TAG, "当前版本名和版本号" + info.versionName + "--" + info.versionCode); return info.versionCode; } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "获取当前版本号出错"); return 0; } } /** * 从服务器获得更新信息 */ public void getUpdateMsg() { class mAsyncTask extends AsyncTask<String, Integer, String> { @Override protected String doInBackground(String... params) { HttpURLConnection connection = null; try { URL url_version = new URL(params[0]); connection = (HttpURLConnection) url_version.openConnection(); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, "GBK")); Log.e(TAG, "bufferReader读到的数据--" + reader); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } return response.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } return null; } @Override protected void onPostExecute(String s) { //回到主线程,更新UI Log.e(TAG, "异步消息处理反馈--" + s); try { JSONObject object = new JSONObject(s); update_versionCode = object.getInt("version"); update_describe = object.getString("describe"); Log.e(TAG, "新版本号--" + update_versionCode); Log.e(TAG, "新版本描述--\n" + update_describe); } catch (JSONException e) { e.printStackTrace(); } if (update_versionCode > getCurrentVersion()) { Log.e(TAG, "提示更新!"); showNoticeDialog(); } else { Log.e(TAG, "已是最新版本!"); } } } new mAsyncTask().execute(version_path); } /** * 显示提示更新对话框 */ private void showNoticeDialog() { new AlertDialog.Builder(context) .setTitle("检测到新版本!") .setMessage(update_describe) .setPositiveButton("下载", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); showDownloadDialog(); } }).setNegativeButton("下次再说", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create().show(); } /** * 显示下载进度对话框 */ public void showDownloadDialog() { progressDialog = new ProgressDialog(context); progressDialog.setTitle("正在下载..."); progressDialog.setCanceledOnTouchOutside(true); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); new downloadAsyncTask().execute(); } /** * 下载新版本应用 */ private class downloadAsyncTask extends AsyncTask<Void, Integer, Integer> { @Override protected void onPreExecute() { Log.e(TAG, "执行至--onPreExecute"); progressDialog.show(); } @Override protected Integer doInBackground(Void... params) { Log.e(TAG, "执行至--doInBackground"); URL url; HttpURLConnection connection = null; InputStream in = null; FileOutputStream out = null; try { url = new URL(apk_path); connection = (HttpURLConnection) url.openConnection(); in = connection.getInputStream(); long fileLength = connection.getContentLength(); File file_path = new File(FILE_PATH); if (!file_path.exists()) { file_path.mkdir(); } out = new FileOutputStream(new File(FILE_NAME));//为指定的文件路径创建文件输出流 byte[] buffer = new byte[1024 * 1024]; int len = 0; long readLength = 0; Log.e(TAG, "执行至--readLength = 0"); while ((len = in.read(buffer)) != -1) { out.write(buffer, 0, len);//从buffer的第0位开始读取len长度的字节到输出流 readLength += len; int curProgress = (int) (((float) readLength / fileLength) * 100); Log.e(TAG, "当前下载进度:" + curProgress); publishProgress(curProgress); if (readLength >= fileLength) { Log.e(TAG, "执行至--readLength >= fileLength"); break; } } out.flush(); return INSTALL_TOKEN; } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } if (connection != null) { connection.disconnect(); } } return null; } @Override protected void onProgressUpdate(Integer... values) { Log.e(TAG, "异步更新进度接收到的值:" + values[0]); progressDialog.setProgress(values[0]); } @Override protected void onPostExecute(Integer integer) { progressDialog.dismiss();//关闭进度条 //安装应用 installApp(); } } /** * 安装新版本应用 */ private void installApp() { File appFile = new File(FILE_NAME); if (!appFile.exists()) { return; } // 跳转到新版本应用安装页面 Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive"); context.startActivity(intent); }}
3、别忘了添加权限
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
学习android 大概半年,菜鸟级别,第一次写博客,自己总结下经验,也抛砖引玉,望高人指点,不知道有没人会看呢?
2 0
- android 自动更新APP版本,并使用ProgressDialog显示进度
- Android App版本自动更新
- Android ProgressDialog显示线程处理进度
- 【android】自定义ProgressDialog实现暂时隐藏进度值并显示等待状态(附源码下载)
- Android实现App版本自动更新
- Android实现App版本自动更新
- Android实现App版本自动更新
- Android实现App版本自动更新
- Android 自动更新 后代通知栏显示进度
- Android中使用ProgressDialog创建进度对话框
- Android的ProgressDialog进度对话框的使用
- android之apk自动更新采用Notification通知提示并显示下载进度
- android之apk自动更新采用Notification通知提示并显示下载进度
- Android进度对话框(ProgressDialog)
- 用android下载一个文件,在ProgressDialog显示下载进度
- 1.5 显示进度对话框---ProgressDialog
- Android 通过蒲公英pgyer的接口 Service 实现带进度下载App 通知栏显示 在线更新 自动更新Demo
- Android 通过蒲公英pgyer的接口 Service 实现带进度下载App 通知栏显示 在线更新 自动更新Demo
- URAL 1788 On the Benefits of Umbrellas
- Yeoman:Web 应用开发流程与工具—AngularJS—Bootstrap—js
- 汇编语言小知识点
- kindeditor上传图片时候,上传成功了,但是页面上却提示失败
- 美国罗斯福纪念公园墙上刻着的一段总统名言
- android 自动更新APP版本,并使用ProgressDialog显示进度
- 新建target后info.plist的路径关联指向问题
- 搜索算法基础之Oil Deposits
- Android屏幕分辨率的问题,dp,px,density等概念
- android-Selector控件点击效果设置
- printf中几个不常用的格式说明
- 判断ios中是否安装了某些软件
- 双向链表的操作
- Android Fragments 详细使用