Android從服務器獲取版本號並下載安裝最新版的應用

簡介

前幾天看了一下黑馬的安全衛士的教程,發現其實內容還是不錯的,纔看到第三天,自定義控件,屬性,類的封裝等等,也學了不少,不過覺得越到後面代碼越冗餘,就介紹一下前兩天課程中的從服務器獲取apk版本號並下載安裝這個功能吧~


工具

  • Android studio
  • Tomcat

具體實現

主界面是一個SplashActivityRelativeLayout佈局
去除標題欄:

   requestWindowFeature(Window.FEATURE_NO_TITLE);

中間是一個圓形進度條

設置TextView的陰影屬性:

         android:shadowDx="1"
        android:shadowDy="1"
        android:shadowRadius="5 "
        android:textSize="30sp"
        android:shadowColor="#f00"

初始化數據:

     /**
     * 初始化數據方法
     */
    private void initData() {
      textView.setText("版本名稱"+getVersion());
        //檢測是否有更新
        //獲取本地版本號
       mLocalVersionCode =  getVersionCode();
        //獲取服務器版本號
        if(SpUtils.getBoolean(getApplicationContext(),ContentValue.OPEN_UPDATE,false)){
            checkVersion();
        }else{
       mHandler.sendEmptyMessageDelayed(ENTER_HOME,4000);
        }
    }

使用的是Hanlder消息機制來傳遞消息
checkVersion()方法開啓線程進行Http請求,從服務器獲取版本號

 /**
     * 檢測版本號
     */
    private void checkVersion() {
        new Thread(){
            @Override
            public void run() {
                super.run();
                Message msg = Message.obtain();
                long startTime = System.currentTimeMillis();
                try {
                    URL url = new URL("http://192.168.191.1:8080/VersionJson.json");
                    //開啓一個連接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                    connection.setConnectTimeout(4000);
                    connection.setReadTimeout(4000);
                    connection.setRequestMethod("GET");
                    if(connection.getResponseCode()==200){
                        InputStream is = connection.getInputStream();
                        InputStreamReader isReader = new InputStreamReader(is);
                        String json = StreamUtil.streamToString(isReader);
                        System.out.println("fdsfasdfa"+json);
                       JSONObject jsonObject = new JSONObject(json);
                        String versionname = jsonObject.getString("versionName");
                        versionDes =  jsonObject.getString("versionDes");
                        String versionCode = jsonObject.getString("versionCode");
                        mDownloadUrl = jsonObject.getString("downloadUrl");
                        Log.d("versionname",versionname);
                        //比對版本號
                        int newVersionCode = Integer.parseInt(versionCode);
                        if(mLocalVersionCode < newVersionCode){
                            //消息機制
                            msg.what =1;
                        }else{
                            msg.what=2;
                        }
                       // textView.setText(json);

                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }finally {
                    long endTime = System.currentTimeMillis();
                    if(endTime-startTime<4000){
                        try {
                            Thread.sleep(4000-(endTime-startTime));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.sendMessage(msg);
                }
            }
        }.start();
    }

服務器上保存的是Json格式的版本信息,獲取Json

獲取本地版本號:

 private int getVersionCode() {
        PackageManager pm = getPackageManager();
        //版本號都在裏面,0代表基本信息
        try {
            PackageInfo packageInfo = pm.getPackageInfo(this.getPackageName(),0);
            //獲取對應版本名稱
            return packageInfo.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

版本號和版本名:

 android:versionCode="1"
    android:versionName="1.0.0"
    >
<!-- android:versionCode 版本號-->
    <!--android:versionName
    1.0.0最後一位代表修復原有版本的Bug
    第二位更新部分功能
    第一位重大更新,重構-->

在和服務器比較版本後如果發現版本不同就彈出提示框,更新和取消:

 private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("版本更新");
        builder.setMessage(versionDes);
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                downLoadApk();
            }
        });
        builder.setNegativeButton("稍後再說",new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enterHome();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                enterHome();
                dialog.dismiss();
            }
        });
        builder.show();
    }

點擊立即更新則會下載URL上的APK安裝包:

 private void downLoadApk() {
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
           String file =  Environment.getExternalStorageDirectory().getAbsoluteFile()+ File.separator+"mobilesafe.apk";
            HttpUtils httpUtils = new HttpUtils();
            httpUtils.download(mDownloadUrl, file, new RequestCallBack<File>() {
                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                        File file = responseInfo.result;
                        Log.d("file test","下載成功");
                    //提示用戶安裝
                    installAPK(file);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    Log.d("file test","下載失敗");
                }
                //剛開始下
                @Override
                public void onStart() {
                    super.onStart();
                    Log.d("file test","下載開始");
                }
                //下載過程中的方法

                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    super.onLoading(total, current, isUploading);
                    Log.d("file test","下中");
                    Log.d("file test","toal"+total);
                    Log.d("file test","current"+current);
                }
            });

        }
    }

此處使用的是xUtils,簡單暴力啊~

最後使用隱式Intent安裝app

 /**
     * 安裝APK
     * @param file
     */
    private void installAPK(File file) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setData(Uri.fromFile(file));//文件數據源
        intent.setType("application/vnd.android.package-archive");
        //startActivity(intent);
        startActivityForResult(intent,0);

    }

最後寫一個淡出的動畫,真個感覺是很好了~

 private void initAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0,1);
        alphaAnimation.setDuration(3000);
        relativeLayout.setAnimation(alphaAnimation);
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章