android APP检测版本更新以及后台服务更新

来源:互联网 发布:苹果young网络客户端 编辑:程序博客网 时间:2024/05/17 05:50

android APP检测版本更新以及后台服务更新

版本更新是获取本地版本号跟服务器版本号进行对比,当有更新的时候服务器会上传新的APK文件,
并且版本号是比没更新的版本号要大的,因此就是版本号的比较来确定是否需要更新。当需要更新
的时候就通过启动后台服务来更新。介绍一下各个知识点:

1、获取本地版本号

//获取本地的版本号private int getVersionCode(){    PackageManager packageManager=getPackageManager();    try {        PackageInfo packageInfo=packageManager.getPackageInfo(getPackageName(), 0);        int versionCode=packageInfo.versionCode;        return versionCode;    } catch (NameNotFoundException e) {        // TODO Auto-generated catch block        e.printStackTrace();    }    return -1;}

调用上面方法返回的就是本地版本号。

2、获取服务器版本号

private void checkVersion() {    final long startTime=System.currentTimeMillis();    new Thread(){        public void run(){            HttpURLConnection conn=null;            Message msg=Message.obtain();            try {                URL url=new URL(GlobalUrl.VERSION_URL);                conn=(HttpURLConnection) url.openConnection();                conn.setRequestMethod("POST");                conn.setConnectTimeout(5000);                conn.setReadTimeout(5000);                conn.connect();                int responseCode=conn.getResponseCode();                if(responseCode==200){                    InputStream inputStream=conn.getInputStream();                    ByteArrayOutputStream out=new ByteArrayOutputStream();                    int len=0;                    byte []buffer=new byte[1024];                    while((len=inputStream.read(buffer))!=-1){                        out.write(buffer, 0, len);                    }                    inputStream.close();                    out.close();                    String result=out.toString();                    System.out.println("VersionResult:"+result);                    String success = null;                    try {                        JSONObject jo=new JSONObject(result);                        success=jo.getString("success");                        System.out.println(success);                    } catch (JSONException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                    Gson gson=new Gson();                    if(success.equals("true")){                        versionData=gson.fromJson(result,VersionData.class);                        version=versionData.version;                        mVersionName=version.releaseCode;      //版本描述                        mVersionCode=version.releaseNumber;    //服务器版本号                        mDesc=version.releaseNotes;            //更新内容                        mDownloadUrl=version.app;              //下载新的APP的地址                        //这里服务器返回的是String类型的版本号,其实版本号应该是int类型的                         //然后判断版本号是否一致                        if(!mVersionCode.equals(getVersionCode()+"")){                            msg.what=CODE_UPDATE_DIALOG;                        }else{                            msg.what=CODE_ENTER_HOME;                        }                    }                }            }catch (MalformedURLException e) {                //url错误                msg.what=CODE_URL_ERROR;                e.printStackTrace();            }catch (IOException e) {                //网络错误                msg.what=CODE_NET_ERROR;                e.printStackTrace();            }finally{                long endTime=System.currentTimeMillis();                long timeUsed=endTime-startTime;                if(timeUsed<2000){                    try {                        Thread.sleep(2000-timeUsed);                    } catch (InterruptedException e) {                        // TODO Auto-generated catch block                        e.printStackTrace();                    }                }                handler.sendMessage(msg);                if(conn!=null){                    //关闭网络连接                    conn.disconnect();                }            }        }    }.start();}//handler处理对应的消息private Handler handler=new Handler(){    public void handleMessage(Message msg) {        switch (msg.what) {        case CODE_UPDATE_DIALOG:           //弹窗是否需要更新            showUpDataDialog();            break;        case CODE_ENTER_HOME:            //进入下个页面。即使忽略更新            jumpNextPage();            break;        case CODE_URL_ERROR:            jumpNextPage();            break;        case CODE_NET_ERROR:            jumpNextPage();            break;        case CODE_JSON_ERROR:            jumpNextPage();            break;        default:            break;        }    };};

获取服务器版本号就是网络请求服务器的数据,得到版本号以及版本描述和新版本的下载地址,将服务器的
版本号跟本地版本号进行对比。大于本地版本号或者跟本地版本号不一致则弹窗提示是否需要更新。
弹窗代码如下:

protected void showUpDataDialog() {    AlertDialog.Builder builder=new AlertDialog.Builder(this);    builder.setTitle("最新版本:"+mVersionName);    builder.setMessage(mDesc);    builder.setPositiveButton("稍后再说", new OnClickListener() {        @Override        public void onClick(DialogInterface dialog, int which) {            jumpNextPage();        }    });    builder.setNegativeButton("立即更新", new OnClickListener() {        @Override        public void onClick(DialogInterface dialog, int which) {            //启动服务            Intent intent=new Intent(SplashActivity.this,UpdateService.class);            intent.putExtra("appName", "CraveHome");            intent.putExtra("url",mDownloadUrl );            startService(intent);             jumpNextPage();        }    });

可以看到取消就直接进入主页面,即使忽略更新。确定就是启动我们的服务来下载最新的APP进行安装。
启动服务需要先新建一个服务。如下:

public class UpdateService extends Service{private String appName;private String url;String target;//通知栏private Notification notification=null;private NotificationManager notificationManager = null;// 通知栏跳转Intentprivate Intent updateIntent = null;private PendingIntent pendingIntent = null;Notification.Builder builder1;@Overridepublic IBinder onBind(Intent intent) {    return null;}@SuppressLint("NewApi") @Overridepublic int onStartCommand(Intent intent, int flags, int startId) {    appName=intent.getStringExtra("appName");    url=intent.getStringExtra("url");    //创建下载APK的路径    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){        target=Environment.getExternalStorageDirectory().getAbsolutePath()+"/crave.apk";    }    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);      builder1 = new Notification.Builder(this);    builder1.setSmallIcon(R.drawable.ic_launch); //设置图标    builder1.setTicker("CraveHome开始下载");     builder1.setContentTitle(appName); //设置标题    builder1.setContentText("正在下载:"); //消息内容    builder1.setWhen(System.currentTimeMillis()); //发送时间    //      builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光    builder1.setAutoCancel(true);//打开程序后图标消失    //      // 设置下载过程中,点击通知栏,回到主界面    //      updateIntent = new Intent(this, MainActivity.class);    //      pendingIntent =PendingIntent.getActivity(this, 0, updateIntent, 0);    //      builder1.setContentIntent(pendingIntent);    notification = builder1.build();    // 通过通知管理器发送通知֪    notificationManager.notify(124, notification);    if(url!=null){        downLoad(url);    }    return super.onStartCommand(intent, flags, startId);}private void downLoad(String url) {    HttpUtils utils=new HttpUtils();    utils.download(url, target, new RequestCallBack<File>() {        @Override        public void onStart() {            System.out.println("CraveHome开始下载");            super.onStart();        }        @SuppressLint("NewApi") @Override        public void onLoading(long total, long current, boolean isUploading) {            System.out.println("正在下载:"+current * 100 / total);            builder1.setContentText("正在下载:"+current * 100 / total+"/100"); //消息内容            if(current==total){                builder1.setContentText("下载完成");                builder1.setDefaults(Notification.DEFAULT_ALL); //设置默认的提示音,振动方式,灯光            }            notification = builder1.build();            notificationManager.notify(124, notification); //通过通知管理器发送通知            super.onLoading(total, current, isUploading);        }        @Override        public void onSuccess(ResponseInfo<File> arg0) {            System.out.println("arg0:"+arg0.result);            Intent intent=new Intent(Intent.ACTION_VIEW);            intent.addCategory(Intent.CATEGORY_DEFAULT);            intent.setDataAndType(Uri.fromFile(arg0.result), "application/vnd.android.package-archive");            //在BroadcastReceiver和Service中startActivity要加上此设置            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);            startActivity(intent);            // 结束service            stopSelf();        }        @Override        public void onFailure(HttpException arg0, String arg1) {            System.out.println(arg1);            // 结束service            stopSelf();        }    });}@Overridepublic void onDestroy() {    System.out.println("serviceDestroy");    super.onDestroy();}

}

然后不要忘记了要在manifest里面进行注册:

 <!-- 注册更新服务 -->    <service android:name="com.demo.UpdateService" />

当然还需要网络访问权限以及文件操作权限:

 <!-- 允许应用程序写入sd卡 --><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- 网络访问权限 --><uses-permission android:name="android.permission.INTERNET" />

以上就是此文内容!
附上Demo下载链接:http://download.csdn.net/detail/qq_30219217/9639022

2 1