android软件更新

软件更新地址:
http://angelsystem.ourangel.cn/Download/app/android/courier.1.0.apk

public void click(View v)
{
    case R.id.layout_updateId_setting:
            {
                 hasNewerSoftware();
                //软件升级
                break;
            }
}

  /**
     *
     * 判断当前软件是否需要更新
     * **/
    private void hasNewerSoftware()
    {
        String url = RequestUrl.URL + RequestUrl.UpdataSoftware + "&account=123";
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                try {
                    if (jsonObject.getString("resultCode").equals("00000")) {
                        mJsonObject = jsonObject;
                        JSONObject data = jsonObject.getJSONObject("data");

                        /*****************服务器软版本号******************/
                        String updateSoftwareUrl = data.getString("updateSoftwareUrl");
                        String softWareName = updateSoftwareUrl.substring(updateSoftwareUrl.lastIndexOf("/") + 1);
                        int start = "courier.".length();
                        String newVersion = softWareName.substring(start,softWareName.indexOf(".apk"));   //courier.1.0.apk
                        /*****************服务器软版本号******************/


                        /*************当前软件的版本号**************/
                        PackageManager packageManager = getPackageManager();
                        // getPackageName()是你当前类的包名,0代表是获取版本信息
                        PackageInfo packInfo = null;
                        try {
                            packInfo = packageManager.getPackageInfo(getPackageName(),0);
                        } catch (PackageManager.NameNotFoundException e) {
                            e.printStackTrace();
                        }
                        String oldVersion = packInfo.versionName;
                        Log.d("Version",oldVersion);
                        /*************当前软件的版本号**************/
                        if(Double.parseDouble(oldVersion) < Double.parseDouble(newVersion))
                        {
                            mHandler.sendEmptyMessage(HAS_NEWER_SOFTWARE);//有新版本的软件可以更新
                        }
                        else
                        {
                            mHandler.sendEmptyMessage(BE_NEWER_SOFTWARE);//当前版本已经是最新版本
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.d("Setting","软件更新失败");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d("setting","网络异常,软件更新失败");
            }
        });
        mQueue.add(jsonObjectRequest);
    }


mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what)
                {
                    case DOWN_OVER:
                        downloadDialog.dismiss();
                        installApk(newFileName);
                        Log.e("updateSoftware","更新完成");
                        break;
                    case DOWN_UPDATE:
                        Log.e("progress",String.valueOf(progress));//更新进度
                        mProgress.setProgress(progress);
                        break;
                    case HAS_NEWER_SOFTWARE:
                        showNoticeDialog();//提示有软件更新
                        break;
                    case BE_NEWER_SOFTWARE:
                        Toast.makeText(SettingActivity.this,"您当前软件版本已经是最新版本",Toast.LENGTH_LONG).show();
                        break;
                    default:
                        break;
                }

            }
        };


    //提示有软件更新
    private void showNoticeDialog(){
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("软件版本更新");
        builder.setMessage(updateMsg);
        builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

 //软件更新对话框
    private void showDownloadDialog(){
        AlertDialog.Builder builder = new Builder(this);
        builder.setTitle("软件版本更新");

        final LayoutInflater inflater = LayoutInflater.from(this);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar)v.findViewById(R.id.progress);

        builder.setView(v);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true;
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();

        prepareUpdate();
    }



//准备更新,从服务器下载apk文件
    private  void prepareUpdate(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                String updateUrl = null;
                try {
                    updateUrl = mJsonObject.getJSONObject("data").getString("updateSoftwareUrl");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                String dirName = "";
                dirName = Environment.getExternalStorageDirectory().getAbsolutePath()+"/MyDownload/";
                File file = new File(dirName);
                if(!file.exists())
                {
                    file.mkdir();
                }
                newFileName = updateUrl.substring(updateUrl.lastIndexOf("/")+1);
                newFileName = dirName + newFileName;
                File newFile = new File(newFileName);
                if(newFile.exists())
                {
                    newFile.delete();//如果存在删除
                }
                URL urlUpdate = null;
                try {
                    urlUpdate = new URL(updateUrl);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                URLConnection con = null;
                try {
                    con = urlUpdate.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //获得文件长度
                 int contentLength = con.getContentLength();
                // 输入流
                InputStream is = null;
                try {
                    is = con.getInputStream();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流
                OutputStream os = null;
                try {
                    os = new FileOutputStream(newFileName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                // 开始读取
                int count = 0;

                try {
                    while ((len = is.read(bs)) != -1 && !interceptFlag) {
                        os.write(bs, 0, len);
                        count += len;
                        progress =(int)(((float)count / contentLength) * 100);
                        mHandler.sendEmptyMessage(DOWN_UPDATE);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(!interceptFlag)
                {
                    mHandler.sendEmptyMessage(DOWN_OVER);//下载完成
                }
                else{
                    Log.d("UpdateSoftware", "=====================更新取消=====================");
                }
                // 完毕,关闭所有链接
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();

    }

//apk文件下载完以后提示用户安装
 //软件安装
    public void installApk(String apk)
    {
        File apkFile = new File(apk);
        if(!apkFile.exists())
        {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.parse("file://"+apkFile.toString()),"application/vnd.android.package-archive");
        startActivity(intent);
    }

/进度条 progress.xml/

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <ProgressBar
        android:id="@+id/progress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="?android:attr/progressBarStyleHorizontal"
        />
</LinearLayout>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值