在我们开发的app中有一个版本更新的提示是非常重要的
其实做版本更新很简单,分几步,按照这几步,一步一步来,化复杂为简单
1、获取本地的版本号和版本名
2、获取服务器端的版本号和版本名
3、比较本地版本号和服务器的版本号,如果服务器上的版本号大于本地版本号,就进行下载
4、下载服务器上的apk文件
5、安装
mainfest权限
<uses-permission android:name='android.permission.INTERNET'/> <!-- 联网权限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <!-- 写入SD卡权限 --> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/> <!-- 在SD卡中创建和删除文件的权限 -->
activity_main布局
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.minmin.downloaddemo.MainActivity"> <TextView android:id="@+id/current_version_code" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> <TextView android:id="@+id/current_version_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" /> </LinearLayout>
download布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_gravity="center_vertical" android:layout_height="match_parent" android:padding="10dp"> <Button android:layout_marginLeft="5dp" android:background="@android:color/transparent" android:id="@+id/m_progress_tv" android:layout_width="30dp" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:gravity="center_vertical" /> <ProgressBar android:id="@+id/m_progress" style="@android:style/Widget.ProgressBar.Horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:layout_toLeftOf="@id/m_progress_tv" android:gravity="center_vertical" /> </RelativeLayout>
主代码,此例中没有对获取服务器的版本号做处理,在比较的时候传入的是两个固定的值,获取服务器上的版本号非常简单,访问后台给的接口,让后解析返回的json字符串就行。
package com.minmin.downloaddemo; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; 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.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class MainActivity extends AppCompatActivity { private TextView current_version_code, current_version_name; private String currentVersionCode = ""; private String serverVersionCode = ""; private MHanlder hanlder; private ProgressBar m_progress; private Dialog dialog; private Button m_progress_tv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); hanlder = new MHanlder(); initView(); getCurrentVersionCode(); compareVersionCode("1", "2"); } /** * 初始化view */ public void initView() { current_version_code = (TextView) findViewById(R.id.current_version_code); current_version_name = (TextView) findViewById(R.id.current_version_name); } /** * 获取当前版本号和版本名 */ public void getCurrentVersionCode() { //获取packagemanager的实例 PackageManager packageManager = getPackageManager(); //getPackageName()是你当前类的包名,0代表是获取版本信息 try { PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0); current_version_code.setText("版本号:"+packageInfo.versionCode + ""); current_version_name.setText("版本名:"+packageInfo.versionName); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } /** * 获取服务器版本号和版本名 */ public void getServerVersionCode() { } /** * 比较当前版本号和服务器上面的版本号 */ public void compareVersionCode(String currentVersionCode, String serverVersionCode) { //如果服务器上的版本大于当前版本,弹出更新提示框 if (Integer.parseInt(serverVersionCode) > Integer.parseInt(currentVersionCode)) { final AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("发现新版本"); builder.setMessage("版本号为:"); builder.setNegativeButton("取消", null); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //开启线程进行下载 new Thread() { @Override public void run() { downLoadApk(); } }.start(); //显示下载的进度框 showProgressBar(); } }); builder.show(); } } /** * 显示下载的进度框 */ public void showProgressBar() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("正在下载..."); View view = LayoutInflater.from(this).inflate(R.layout.download, null); m_progress = (ProgressBar) view.findViewById(R.id.m_progress); m_progress_tv = (Button) view.findViewById(R.id.m_progress_tv); builder.setView(view); dialog = builder.show(); dialog.setCancelable(false); } @Override protected void onDestroy() { super.onDestroy(); dialog.dismiss(); } /** * 下载apk */ public void downLoadApk() { try { // URL url = new URL("http://hxyiyo.com/ydjx_tV1.0.apk"); URL url = new URL("http://p.gdown.baidu.com/d8e1f2a4fc89522042331eb015df5381fce8c2f605093c3384ce030e772dfcad29ffc4aa1561e1fb5d74f30a61b19e97dd4a67fa386ba875b15120bbe9c0bc567855c53a12f37032d30daa82374a28ae8991363886088bd93a1cc9aad85a6330dc3786dbc59af6bc7bf7ffb53b2e996e2cbee51cb9082c35e04d957a82b48a2693d95aee2dfac6769cb040c1abf75acba2a11d92df2d5f243c0c885975f57fb3d9482e942e883dce45d04087a9a06f590e12b379b6a29604ef4054c224916ee945bc250ae8f36e3275a2e5a62b49e982f250218c6dfb63bcc2248247dac8f136cbc6dfe1e565baedc1250aa4f4faf97145a3f09b40126a201db0cebb0eb178e506f30323cfc16a38aad4007dd3d130f9d60256eb1a5d875a8407f8befe378ca50f596e0fecec67b4e2c09ca0dd68e594830643ead01537ee"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); BufferedInputStream bis = new BufferedInputStream(connection.getInputStream()); File file = new File(Environment.getExternalStorageDirectory() + "/newap.apk"); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file)); int fileLength = connection.getContentLength(); int downloadLength = 0; int progressLength = 0; int n = 0; byte[] buffer = new byte[1024]; while ((n = bis.read(buffer, 0, buffer.length)) != -1) { bos.write(buffer, 0, n); downloadLength += n; progressLength = (int) (((float) downloadLength / fileLength) * 100); Message msg = new Message(); msg.arg1 = progressLength; hanlder.sendMessage(msg); } bis.close(); bos.close(); connection.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private class MHanlder extends Handler { @Override public void handleMessage(Message msg) { super.handleMessage(msg); m_progress.setProgress(msg.arg1); m_progress_tv.setText(msg.arg1 + "%"); if (msg.arg1 == 100) { dialog.dismiss(); Intent intent = new Intent(Intent.ACTION_VIEW); String path = Environment.getExternalStorageDirectory() + "/newap.apk"; intent.setDataAndType(Uri.fromFile(new File(path)), "application/vnd.android.package-archive"); startActivity(intent); } } } }