安卓版本更新的逻辑

对于安卓的版本更新,相信很多人都不会陌生,它主要包括强制更新和正常提示更新,现在就对于这方面我做一个简单的小结,希望对大家有用!!!

1. 首先版本更新的操作需要在进入主页面前执行,就是说最好不在主页面执行,才能显得正常,这个页面一般就是我们说的欢迎页面WelcomeActivity

2. 通过获取服务器端的versioncode和本地获取的eversioncode进行比较,如果服务器code>本地code,说明已经出现了新的版本,再判断服务器返回的另外一个字段foce的值判断是否需要强制更新!

<pre style="font-family: 宋体; font-size: 11.3pt; background-color: rgb(255, 255, 255);">

这个是进入欢迎页执行网络请求: 
 UpDateVersion updatever;
 
  updatever = new UpDateVersion(StartActivity.this);
        updatever.setNewVersionListener(new UpDateVersion.NewVersionListener() {
            @Override
            public void onNewVersion() {
                myHandler.removeCallbacksAndMessages(null);
            }
        });
        updatever.setUpdateCancelListener(new UpDateVersion.UpdateCancelListener() {
            @Override
            public void onUpdateCancel() {
                startMain();
            }
        });
        Runnable runnable=new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                updatever.update();
            }
        };

这个是执行网络请求和更新处理逻辑,里面用到了自自定义监听器和okhttp

<pre name="code" class="java">package com.joytouch.superlive.widget.updateVersion;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.joytouch.superlive.R;
import com.joytouch.superlive.app.Preference;
import com.joytouch.superlive.javabean.SoftwareUpdate;
import com.joytouch.superlive.utils.HttpRequestUtils;
import com.joytouch.superlive.utils.MD5Util;
import com.joytouch.superlive.utils.PackageUtils;
import com.joytouch.superlive.utils.city.File_Util;
import com.joytouch.superlive.utils.view.DownLoadApkTask;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import okhttp3.FormBody;

/**
 * Created by Administrator on 5/11 0011.
 */
public class UpDateVersion {
    private final SharedPreferences sp;
    /**
     flag
     普通升级--[1]--杀进程重启后有提示(暂不升级,立刻升级),点击返回键,不退出app,不做页面跳转;
     中级升级--[2]--杀进程重启,挂起后再启动提示(暂不升级,立刻升级),点击返回键,不退出app,不做页面跳转;
     强制升级--[3]--任何方式进入app,提示升级(立刻升级);点击返回键,直接退出;
     */
    private   Context context;
    private String flag="0";//默认普通升级
    private NewVersionListener newVersionListener_;
    private UpdateCancelListener updateCancelListener_;
    private boolean isUpdate=false;

    public UpDateVersion(Context context) {
        this.context=context;
        sp = context.getSharedPreferences(Preference.preference,
                Context.MODE_PRIVATE);
    }



    public void update(){
        String channel_b = PackageUtils.getSource(context);
        String codeVer_b = String.valueOf(PackageUtils.getVersionCode(context));
        String softname_b = Preference.softname;
        String ver_b = PackageUtils.getVersionName(context);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("channel", channel_b);
        map.put("codeVer", codeVer_b);
        map.put("softname", softname_b);
        map.put("ver", ver_b);
        map.put("version", Preference.version);
        String sign = getMD5(map);

        FormBody.Builder build=new FormBody.Builder();
        build
                .add("channel", channel_b)
                .add("codeVer", codeVer_b)
                .add("softname", softname_b)
                .add("ver", ver_b)
                .add("version", Preference.version)
                .add("sign", sign)
                .build();
        new HttpRequestUtils((Activity) context).httpPost(Preference.update_url, build,
                new HttpRequestUtils.ResRultListener() {
                    @Override
                    public void onFailure(IOException e) {
                        //获取网络数据失败会跳转到主页面
//                        Intent intent=new Intent(context, MainActivity.class);
//                        context.startActivity(intent);
                    }

                    @Override
                    public void onSuccess(String json) {
                        Log.e("版本更新", json);
                        String json_ = File_Util.readAssets(context, "banben.json");
                        Gson gson = new Gson();
                        SoftwareUpdate Bean = gson.fromJson(json, SoftwareUpdate.class);

                            //本版本
                            int version_code = PackageUtils.getVersionCode(context);
                            int newVersion = 0;

                            String ver = Bean.ver;
                            String updateDescription = Bean.updateDescription;
                            String downloadUrl = Bean.downloadUrl;
                            String codeVer = Bean.codeVer;
                            int force = Bean.force;

                            if (!TextUtils.isEmpty(codeVer)) {
                                newVersion = Integer.parseInt(codeVer);
                            }
//                            当本地的versioncode小于服务器传来的newVersion时,并且force>0,才会提示更新
                            if (version_code < newVersion) {
                                //后台数据force,force>1升级
                                if (force >0) {
                                    if (newVersionListener_ != null) {
                                        newVersionListener_.onNewVersion();
                                    }
                                    setUpdate(Bean);
                                } else {
                                    updateCancelListener_.onUpdateCancel();
                                }
                                //本地保存一个forcr_,用于判定是哪种类型的更新
                                sp.edit().putInt("updateversion",force).commit();
                            }else{
                                //force_==4,表示不属于任何一种更新
                                sp.edit().putInt("updateversion",4).commit();
                                updateCancelListener_.onUpdateCancel();
//                                ((Activity) context).finish();
                            }
                    }
                });
    }

    private static Dialog dialog;

    private void setUpdate(final SoftwareUpdate bean) {
        dialog = new Dialog(context, R.style.Dialog_bocop);
        dialog.setContentView(R.layout.updateversiondialog);
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失dialog
        dialog.setCancelable(false);
        TextView tvtv=(TextView)dialog.findViewById(R.id.tvtv);
        tvtv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        TextView tv_title = (TextView) dialog.findViewById(R.id.tv_title);
        TextView tv_content = (TextView) dialog.findViewById(R.id.tv_content);
        tv_content.setVisibility(View.VISIBLE);
        tv_title.setText("升级提示");
        tv_content.setText(bean.updateDescription);

        Button btn_cancel = (Button) dialog.findViewById(R.id.btn_cancel);
        Button btn_submit = (Button) dialog.findViewById(R.id.btn_submit);

        //强制升级,force=3;
        //中等升级,force=2;
        //普通升级:force=1;
        //不升级,force=0;没有提示,>0都有提示
        if ("3".equals(bean.force+"")) {
            btn_cancel.setVisibility(View.GONE);
        }
        btn_cancel.setText("暂不更新");
        btn_submit.setText("立刻下载");

        btn_cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                isUpdate = true;
                new DownLoadApkTask((Activity) context, "update.apk", bean.downloadUrl).execute();
                dialog.dismiss();
            }
        });

        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub
                if (!isUpdate &&updateCancelListener_ != null) {
                    if ("3".equals(bean.force+"")) {
                        //强制,后台挂起与杀进程都会提示,且退出程序
                        System.exit(0);
                    }else if ("2".equals(bean.force+"")){
                        updateCancelListener_.onUpdateCancel();
                        //中等更新,杀进程,后台挂起都会提示

                    }else if ("1".equals(bean.force+"")){
                        updateCancelListener_.onUpdateCancel();
                        //普通更新,只有杀进程才会提示

                    }else{
                        updateCancelListener_.onUpdateCancel();
                    }

                }
            }
        });

        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }
    private static String getMD5(HashMap<String, String> map) {

        ArrayList<String> keyList = new ArrayList<String>();
        for (String key : map.keySet()) {
            keyList.add(key);
        }
        Collections.sort(keyList);

        StringBuffer buffer = new StringBuffer();
        buffer.append(Preference.key_f);
        for (String key : keyList) {
            buffer.append(map.get(key));
        }
        buffer.append(Preference.key_b);
        return MD5Util.md5(buffer.toString());
    }


    public void cancel() {

    }

    public interface NewVersionListener {
        public void onNewVersion();
    }

    public interface UpdateCancelListener {
        public void onUpdateCancel();
    }

    public void setNewVersionListener(NewVersionListener newVersionListener) {
        newVersionListener_ = newVersionListener;
    }
    public void setUpdateCancelListener(UpdateCancelListener updateCancelListener) {
        updateCancelListener_ = updateCancelListener;
    }


}

 okhttp网络请求工具类 

package com.joytouch.superlive.utils;

import android.app.Activity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.joytouch.superlive.R;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by yj on 2016/4/22.
 * 使用方式:
     FormBody.Builder build=new FormBody.Builder();
     build.add("token", "AFAF2806-5AE1-3D90-4C18-0050AF2DE2D")
     .add("phone", "1")
     .add("content", "helougewei")
     .add("version", "4")
     .add("zb_id", "41622")
     .add("show_type", "chat")
     .build();
      new HttpRequestUtils(ChargeActivity.this).httpPost("http://www.qiuwin.com/I/v1.php/SuperLive4/ChatClient.json", build,
      new HttpRequestUtils.ResRultListener() {
        @Override
        public void onFailure(IOException e) {}
        @Override
        public void onSuccess(String json) {
        Gson gson = new Gson();
        BaseBean  bean = gson.fromJson(json, BaseBean.class);
        Log.e("测试",bean.message);}
        });
 * okhttp请求封装累
 */
public class HttpRequestUtils {
    private OkHttpClient httpClient;
    private Call call;
    private Activity activity;
    private long timeout = 10;
    private LinearLayout loadingfailed;
    private LinearLayout refreshll;
    private ImageView refresh;
    private View view;
    private boolean isloading = false;
    private String type;
    public HttpRequestUtils(Activity activity,View view,boolean isup) {
        //创建okhttp对象
        httpClient = new OkHttpClient();
        httpClient.newBuilder().connectTimeout(timeout, TimeUnit.SECONDS)
        .readTimeout(timeout,TimeUnit.SECONDS)
        .writeTimeout(timeout, TimeUnit.SECONDS);
        this.view = view;
        this.activity = activity;
        if(!isup) {
            loadingfailed = (LinearLayout) view.findViewById(R.id.loading_failed);
            refreshll = (LinearLayout) view.findViewById(R.id.refreshll);
            refresh = (ImageView) view.findViewById(R.id.refresh_logo);
            isloading = true;
        }else{
            isloading = false;
        }


    }
    public HttpRequestUtils(Activity activity) {
        //创建okhttp对象
        httpClient = new OkHttpClient();
        httpClient.newBuilder().connectTimeout(timeout, TimeUnit.SECONDS)
                .readTimeout(timeout, TimeUnit.SECONDS)
                .writeTimeout(timeout, TimeUnit.SECONDS);
        this.activity = activity;
        isloading = false;
    }
    //取消请求
    private void cancel(){
        if(call!= null){
            call.cancel();
        }
    }
    //get请求
    public void httpGet(String url, final ResRultListener resRultListener){
        //创建一个请求
        final Request request = new Request.Builder().url(url).build();
        //创建一个呼叫请求
        call = httpClient.newCall(request);
        //创建一个异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if(resRultListener !=null){
                    resRultListener.onFailure(e);
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (resRultListener != null) {
                            resRultListener.onSuccess(json);
                        }
                    }
                });


            }
        });
    }
    //post的请求
    public void httpPost(final String url , final FormBody.Builder builder,final ResRultListener resRultListener){

        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .url(url).post(body).build();
        String bodycontent = "";
        int length = builder.build().size();
        if(LogUtils.isOpen()) {
            for (int i = 0; i < length; i++) {
                bodycontent = bodycontent + builder.build().encodedName(i) + "=" + builder.build().encodedValue(i)+"&";
            }
        }
        LogUtils.e("builder", bodycontent);
        if(isloading) {
            loading();
        }
        //创建一个呼叫请求
        call = httpClient.newCall(request);
        //创建一个异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(resRultListener !=null){

                            resRultListener.onFailure(e);
                            if(isloading) {
                                loadingFailed(url,builder,resRultListener);
                            }
//                            LogUtils.e("exception", e.getMessage());
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                LogUtils.e("json",json);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (resRultListener != null) {
                            if(isloading) {
                                loadinSuccess();
                            }
                            resRultListener.onSuccess(json);
                        }
                    }
                });


            }
        });

    }

    //post的请求上传单张图片
    public void httpPostImage(String url ,String filekey,String filePath,String imageName,final ResRultListener resRultListener){
        File file = new File(filePath);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart(filekey, imageName, RequestBody.create(MediaType.parse("image/png"), file));
        Request request = new Request.Builder()
                .url(url).post(builder.build()).build();
        //创建一个呼叫请求
        call = httpClient.newCall(request);
        //创建一个异步请求
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (resRultListener != null) {
                            resRultListener.onFailure(e);

                        }
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (resRultListener != null) {

                            resRultListener.onSuccess(json);
                        }
                    }
                });


            }
        });

    }
//请求结果回调
public interface ResRultListener{
    void onFailure(IOException e);
   void onSuccess(String json);
}
    public  void loading(){
        if(this.view == null){
            LogUtils.e("sssssssssssss","///");
        }
        view.setVisibility(View.VISIBLE);
        loadingfailed.setVisibility(View.GONE);
        refreshll.setVisibility(View.VISIBLE);
        RotateAnimation an = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        an.setInterpolator(new LinearInterpolator());//不停顿
        an.setRepeatCount(-1);//重复次数
        an.setFillAfter(true);//停在最后
        an.setDuration(600);
        refresh.startAnimation(an);

    }
    public void loadingFailed(final String url , final FormBody.Builder builder,final ResRultListener resRultListener){
        loadingfailed.setVisibility(View.VISIBLE);
        refreshll.setVisibility(View.GONE);
        refresh.clearAnimation();
        loadingfailed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LogUtils.e("loadingfailed", url);
                httpPost(url, builder, resRultListener);
            }
        });

    }
    public void loadinSuccess(){
        refresh.clearAnimation();
        view.setVisibility(View.GONE);
        loadingfailed.setVisibility(View.GONE);
    }

}

在使用Android studio时需要的build.gradle文件

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.github.ctiao:DanmakuFlameMaster:0.4.6'
    compile files('libsbammsdk.jar')
    compile files('libs/universal-image-loader-1.9.4-SNAPSHOT.jar')
    compile files('libstpmime-4.1.3.jar')
    compile files('libs/gson-2.2.1.jar')
    compile files('libs/jpush-android-2.1.0.jar')
    compile files('libs/mta-sdk-1.6.2.jar')
    compile files('libs/open_sdk_r5509.jar')
    compile files('libs/SocialSDK_QQZone_3.jar')
    compile files('libs/SocialSDK_tencentWB_1.jar')
    compile files('libs/SocialSDK_WeiXin_2.jar')
    compile files('libs/wkimageloader.jar')
    compile 'com.umeng.analytics:analytics:latest.integration'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.android.support:support-v4:22.2.1'
    compile 'com.zhy:flowlayout-lib:1.0.1'
    compile 'com.qiniu:happy-dns:0.2.7'
    //主播特点标签
    compile 'com.android.support:recyclerview-v7:24.0.0-alpha1'
    compile 'com.lsjwzh:materialloadingprogressbar:0.5.8-RELEASE'
    compile 'com.flyco.dialog:FlycoDialog_Lib:1.1.0@aar'
    compile 'com.flyco.animation:FlycoAnimation_Lib:1.0.0@aar'
    compile 'com.nineoldandroids:library:2.4.0'
    compile files('libshttpserver-0.1.2.jar')
    compile files('libshttputils-1.4.0.jar')
    compile files('libsio-1.6.0.jar')
    compile files('libstils3.1.8.jar')
    compile files('libs/SocialSDK_tencentWB_2.jar')
    compile files('libs/commons-codec-1.4.jar')
    compile files('libs/pldroid-player-1.2.2.jar')
    compile files('libs/alipaySDK-20150610.jar')
    compile files('libs/commons-codec-1.4.jar')
    compile files('libs/pldroid-player-1.2.2.jar')
    compile files('libs/support-v13-13.0.0.jar')
    compile files('libs/pldroid-camera-streaming-1.7.1.jar')
    compile files('libs/armeabi/BaiduNaviSDK_3.2.0.jar')
    compile files('libs/armeabi/httpmime-4.1.2.jar')
    compile files('libs/BaiduNaviSDK_3.2.0.jar')
}



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值