Android 版本更新

释放双眼,带上耳机,听听看~!

商城项目功能上基本结束,现在正在考虑一下 上线的问题,因为这是第一版所以后面一定会有版本更新的问题,所以昨天搞了一下版本更新,今天抽出时间做一下总结,这里我参考了 https://github.com/chiclaim/android-app-update  朋友的博客 简单的 修改了一下逻辑 用到了自己的项目当中。

废话不多说 接下来 说一下 版本更新的 整个流程 包括跟后台的配合。所有的注意事项都写在注释里面

 

MainActivity 判断版本号 是否调用更新方法,这里我用了Volley
网络请求框架,主要是从后台服务器获取当前最新的版本号VersionName 这里是1.1.0 什么的 其实我本意想判断VersionCode 这个是整型int 这个判断起来比较直观,但是后台不想改动他的代码所以这里直接判断后台VersionName 跟 当前VersionName字符串是否相等,后台的VersionName 是最新的 如果相等当前用户的手机就是最新版本 否则就更新。。。。。

 

      mHttpHelper.sendJsonRequest("TAG", reqData1, Parameter, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
Log.i("获取版本更新数据", String.valueOf(response.getJSONObject("rspCode").getString("code")));
String resCode = response.getJSONObject("rspCode").getString("code");
                            if (resCode.equals("0000")) {
//                                "{"appName":"android","id":1,"app":"0","emergency":"0","note":"第一版","version":"1.1.0"}"
try {
String jsonObject1 = response.getString("message");
JSONObject jsonObject = new JSONObject(jsonObject1);
//                                    String appName = jsonObject.getString("appName");
//                                    String id = jsonObject.getString("id");
//                                    String note = jsonObject.getString("note");
String NewVersionName = jsonObject.getString("version");
//                                    Log.e("版本更新数据", appName);
//                                    Log.e("版本更新数据", id);
//                                    Log.e("版本更新数据", note);
//                                    Log.e("版本更新数据", NewVersionName);
                                    //获取当前程序的版本号
String PerVersionName = null;
                                    try {
PackageManager packageManager = getPackageManager();
// getPackageName()是你当前类的包名,0代表是获取版本信息
PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
PerVersionName = packInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
if(! PerVersionName.equals(NewVersionName)){
doNewVersionUpdate(PerVersionName,NewVersionName);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
//                                Toast.makeText(getContext(), "请检查网络连接", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
                new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
}

 

MainActivity 版本更新方法  这里我用了一个Dialog 弹出框 提示用户进行更新操作

 

 /**
     * 提示更新新版本
     *
     https://github.com/chiclaim/android-app-update
     */
private void doNewVersionUpdate(String PerVersionName,String NewVersionName) {
String str = "当前版本:" + PerVersionName + " ,发现新版本:" + NewVersionName + " ,是否更新?";
Dialog dialog = new AlertDialog.Builder(this).setTitle("更新提示").setMessage(str).setIcon(R.mipmap.login_logo)
// 设置内容
.setPositiveButton("更新",// 设置确定按钮
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
ApkUpdateUtils.download(getApplication(), "http://age谁的风格大方u.apk", getResources().getString(R.string.app_name));
}
})
.setNegativeButton("暂不更新",
                        new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
                                                int whichButton) {
// 点击"取消"按钮之后退出程序
//                                finish();
dialog.dismiss();
}
}).create();// 创建
        // 显示对话框
dialog.show();
}
}

 

 

DownManager 下载App的管理器

 

package com.ingkoo.AppVersionUpdate;
import android.app.DownloadManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
/**
 * Created by chiclaim on 2016/05/18
 */
public class FileDownloadManager {
private DownloadManager dm;
    private Context context;
    private static FileDownloadManager instance;
    private FileDownloadManager(Context context) {
dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        this.context = context.getApplicationContext();
}
public static FileDownloadManager getInstance(Context context) {
if (instance == null) {
instance = new FileDownloadManager(context);
}
return instance;
}
/**
     * @param uri
* @param title
* @param description
* @return download id
     */
public long startDownload(String uri, String title, String description) {
DownloadManager.Request req = new DownloadManager.Request(Uri.parse(uri));
req.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
//req.setAllowedOverRoaming(false);
req.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//设置文件的保存的位置[三种方式]
        //第一种
        //file:///storage/emulated/0/Android/data/your-package/files/Download/update.apk
req.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, "update.apk");
//第二种
        //file:///storage/emulated/0/Download/update.apk
        //req.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "update.apk");
        //第三种 自定义文件路径
        //req.setDestinationUri()
        // 设置一些基本显示信息
req.setTitle(title);
req.setDescription(description);
req.setMimeType("application/vnd.android.package-archive");
        return dm.enqueue(req);
//long downloadId = dm.enqueue(req);
        //Log.d("DownloadManager", downloadId + "");
        //dm.openDownloadedFile()
}
/**
     * 获取文件保存的路径
     *
     * @param downloadId an ID for the download, unique across the system.
     *                   This ID is used to make future calls related to this download.
     * @return file path
     * @see FileDownloadManager#getDownloadUri(long)
     */
public String getDownloadPath(long downloadId) {
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
Cursor c = dm.query(query);
        if (c != null) {
try {
if (c.moveToFirst()) {
return c.getString(c.getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI));
}
} finally {
c.close();
}
}
return null;
}
/**
     * 获取保存文件的地址
     *
     * @param downloadId an ID for the download, unique across the system.
     *                   This ID is used to make future calls related to this download.
     * @see FileDownloadManager#getDownloadPath(long)
     */
public Uri getDownloadUri(long downloadId) {
return dm.getUriForDownloadedFile(downloadId);
}
public DownloadManager getDm() {
return dm;
}
/**
     * 获取下载状态
     *
     * @param downloadId an ID for the download, unique across the system.
     *                   This ID is used to make future calls related to this download.
     * @return int
     * @see DownloadManager#STATUS_PENDING
     * @see DownloadManager#STATUS_PAUSED
     * @see DownloadManager#STATUS_RUNNING
     * @see DownloadManager#STATUS_SUCCESSFUL
     * @see DownloadManager#STATUS_FAILED
     */
public int getDownloadStatus(long downloadId) {
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
Cursor c = dm.query(query);
        if (c != null) {
try {
if (c.moveToFirst()) {
return c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
}
} finally {
c.close();
}
}
return -1;
}
}

 

 

package com.ingkoo.AppVersionUpdate;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;
/**
 * Created by chiclaim on 2016/05/18
 */
public class ApkUpdateUtils {
public static final String TAG = ApkUpdateUtils.class.getSimpleName();
    private static final String KEY_DOWNLOAD_ID = "downloadId";
    public static void download(Context context, String url, String title) {
long downloadId = SpUtils.getInstance(context).getLong(KEY_DOWNLOAD_ID, -1L);
        if (downloadId != -1L) {
FileDownloadManager fdm = FileDownloadManager.getInstance(context);
            int status = fdm.getDownloadStatus(downloadId);
Log.e("status", String.valueOf(status));
            if (status == DownloadManager.STATUS_SUCCESSFUL) {
//启动更新界面
Uri uri = fdm.getDownloadUri(downloadId);
                if (uri != null) {
if (compare(getApkInfo(context, uri.getPath()), context)) {
startInstall(context, uri);
                         return;
} else {
fdm.getDm().remove(downloadId);
}
}
start(context, url, title);
} else if (status == DownloadManager.STATUS_FAILED) {
start(context, url, title);
} else {
Log.d(TAG, "apk is already downloading");
}
} else {
start(context, url, title);
}
}
private static void start(Context context, String url, String title) {
long id = FileDownloadManager.getInstance(context).startDownload(url,
title, "下载完成后点击打开");
SpUtils.getInstance(context).putLong(KEY_DOWNLOAD_ID, id);
Log.d("status", "apk start download " +SpUtils.getInstance(context).getLong(KEY_DOWNLOAD_ID, (long) -1));
}
public static void startInstall(Context context, Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(uri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
/**
     * 获取apk程序信息[packageName,versionName...]
     *
     * @param context Context
     * @param path    apk path
     */
private static PackageInfo getApkInfo(Context context, String path) {
PackageManager pm = context.getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
        if (info != null) {
String packageName = info.packageName;
String version = info.versionName;
Log.d(TAG, "packageName:" + packageName + ";version:" + version);
//            String appName = pm.getApplicationLabel(appInfo).toString();
//            Drawable icon = pm.getApplicationIcon(appInfo);//得到图标信息
return info;
}
return null;
}
/**
     * 下载的apk和当前程序版本比较
     *
     * @param apkInfo apk file's packageInfo
     * @param context Context
     * @return 如果当前应用版本小于apk的版本则返回true
     */
private static boolean compare(PackageInfo apkInfo, Context context) {
if (apkInfo == null) {
return false;
}
String localPackage = context.getPackageName();
        if (apkInfo.packageName.equals(localPackage)) {
try {
PackageInfo packageInfo = context.getPackageManager().getPackageInfo(localPackage, 0);
                if (apkInfo.versionCode > packageInfo.versionCode) {
return true;
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
return false;
}
}

 

人已赞赏
Android文章

Android ORM框架 GreenDao3.0的使用

2020-3-25 16:58:47

Android文章

Android Dialog

2020-3-25 17:49:52

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索