APP自动更新(全)

自动更新步骤:

1.  在MainActivity.java中检查版本:

public class MainActivity extends BaseActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private boolean isUpdating = false;
    private String mDownloadUrl;
    private String mDescribe;
    

    ……

    public void onResume() {
        super.onResume();
        if (!isUpdating) {
//            checkVersion();
        }
    }

    //App检查更新
    private void checkVersion() {
        HashMap<String, Object> baseParam = WebFrontUtil.getBaseParam();
        OkHttpUtil.post(TAG, WebApi.APP_UPDATE, baseParam, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.d(TAG, "checkVersion: e=" + e.toString());
            }

            @Override
            public void onResponse(String response, int id) {
                Log.d(TAG, "checkVersion: " + response.toString());
                try {
                    JSONObject object = new JSONObject(response);
                    if ((int)object.get("code") == 200) {
                        JSONObject object1 = object.getJSONObject("data");
                        VersionBean versionBean = new Gson().fromJson(object1.toString(),VersionBean.class);
                        if (getVersionCode() < versionBean.getVersion()) {
                            mDownloadUrl = versionBean.getDownloadJhUrl();
                            mDescribe = versionBean.getDescribe();
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                if (!getPackageManager().canRequestPackageInstalls()) {
                                    AlertDialog.Builder quitBuilder = new AlertDialog.Builder(MainActivity.this,AlertDialog.THEME_TRADITIONAL);
                                    quitBuilder.setTitle("需要打开允许来自此来源,请去设置中开启此权限");
                                    quitBuilder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialogInterface, int i) {
                                            toInstallPermissionSettingIntent();
                                        }
                                    });
                                    quitBuilder.create().show();
                                } else {
                                    updateApp();
                                }
                            } else {
                                updateApp();
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 开启安装未知来源权限
    private void toInstallPermissionSettingIntent() {
        Uri packageURI = Uri.parse("package:"+getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        startActivityForResult(intent, 100);
    }

    private void updateApp() {
        isUpdating = true;
        new DownloadUtils(MainActivity.this, getSupportFragmentManager(), mDownloadUrl, mDescribe);
    }


    //获取版本
    private int getVersionCode() {
        int localVersion = 0;
        try {
            PackageInfo packageInfo = getApplicationContext()
                    .getPackageManager()
                    .getPackageInfo(getPackageName(), 0);
            localVersion = packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return localVersion;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            updateApp();
        }
    }

VersionBean.java

public class VersionBean {
    private String describe;
    private String downloadUrl;
    private String downloadJhUrl;
    private int version;

    public String getDescribe() {
        return describe;
    }
    
    public void setDescribe(String describe) {
        this.describe = describe;
    }

    public String getDownloadUrl() {
        return downloadUrl;
    }

    public void setDownloadUrl(String downloadUrl) {
        this.downloadUrl = downloadUrl;
    }

    public String getDownloadJhUrl() {
        return downloadJhUrl;
    }

    public void setDownloadJhUrl(String downloadJhUrl) {
        this.downloadJhUrl = downloadJhUrl;
    }

    public int getVersion() {
        return version;
    }

    public void setVersion(int version) {
        this.version = version;
    }
}

3. DownloadUtils.java

private static final String TAG = "DownloadUtils";

    private Context mContext;
    private FragmentManager mFragmentManager;
    private File mFile;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if (mDownloadProgress != null) {
                        float progress = (float) msg.obj;
                        if (progress < mDownloadProgress.getMaxProgress()) {
                            mDownloadProgress.setState(DownloadProgressButton.STATE_DOWNLOADING);
                            mDownloadProgress.setProgressText("下载中", progress);
                        } else {
                            mDownloadProgress.setState(DownloadProgressButton.STATE_FINISH);
                            mDownloadProgress.setCurrentText("下载完成,点击安装");
                            mDownloadProgress.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (mFile != null) {
                                        installApk(mFile);
                                    }
                                }
                            });
                        }
                    }
                    break;
            }
        }
    };

    private DownloadProgressButton mDownloadProgress;
    private long[] mHits = new long[4];
    private boolean finish = true;

    public DownloadUtils(Context context, FragmentManager fragmentManager, String url, String content) {
        mContext = context;
        mFragmentManager = fragmentManager;
        if (url != null && !url.equals("")) {
            initDialog(content);
            downloadFile(url);
        }
    }

    private void initDialog(String content) {
        content = content == null || content.equals("")
                ? "发现新版本,为了不影响您的使用,正在升级..." : content;

        final String finalContent = content;
        new TDialog.Builder(mFragmentManager)
                .setLayoutRes(R.layout.dialog_update_progress)
                .setScreenWidthAspect(((Activity) mContext), 0.8f)
                .setTag("DialogTest")
                .setDimAmount(0.6f)
                .setGravity(Gravity.CENTER)
                .setCancelableOutside(false)
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        if (finish) {
                            ActivityCollector.finishAll();
                        }
                    }
                })
                .setOnBindViewListener(new OnBindViewListener() {
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        bindViewHolder.setText(R.id.tv_content, finalContent);
                        mDownloadProgress = bindViewHolder.getView(R.id.download_bar);
                        mDownloadProgress.setButtonRadius(30);
                        mDownloadProgress.setShowBorder(false);
                        mDownloadProgress.postInvalidate();
                        mDownloadProgress.setState(DownloadProgressButton.STATE_DOWNLOADING);
                        mDownloadProgress.setProgressText("下载中", 0);
                    }
                })
                .addOnClickListener(R.id.tv_title)//R.id.tv_cancel, R.id.tv_confirm,
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.tv_title:
                                System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
                                mHits[mHits.length - 1] = SystemClock.uptimeMillis();
                                if (mHits[0] >= (SystemClock.uptimeMillis() - 1000)) {
                                    tDialog.dismiss();
                                    finish = false;
                                }
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    private void downloadFile(final String url) {

        new Thread() {
            @Override
            public void run() {
                try {
                    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
                    conn.setConnectTimeout(5000);
                    //获取到文件的大小
//                    mDownloadProgress.setMaxProgress(conn.getContentLength());
                    InputStream is = conn.getInputStream();
                    mFile = new File(getRoot(), "nmpa.apk");
//                    mFile = new File(getRoot(), "firef.apk");
                    FileOutputStream fos = new FileOutputStream(mFile);
                    BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] buffer = new byte[1024];
                    int len;
                    int total = 0;

                    float c = 0;
                    while ((len = bis.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                        //获取当前下载量
                        total += len;
                        float nextC = ((float) total / conn.getContentLength()) * 100;
                        Message message = mHandler.obtainMessage();
                        if (message == null) {
                            message = new Message();
                        }
                        if (nextC - c > 0.1) {
                            message.what = 0;
                            message.obj = nextC;
                            mHandler.sendMessage(message);
                            c = nextC;
                        } else if (total == conn.getContentLength()) {
                            message.what = 0;
                            message.obj = nextC;
                            mHandler.sendMessage(message);
                            c = nextC;
                        }
                    }
                    fos.close();
                    bis.close();
                    is.close();
//                    installApk(file);
                    installApk(mFile);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    //安装apk
    private void installApk(File file) {
        Log.e(TAG,"file="+file);
        //版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.nmpa.nmpaapp.file.provider", file);//在AndroidManifest中的android:authorities值
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            install.setDataAndType(apkUri, "application/vnd.android.package-archive");
            mContext.startActivity(install);
        } else {
            Intent intent = new Intent();
            //执行动作
            intent.setAction(Intent.ACTION_VIEW);
            //执行的数据类型
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }


    private File getRoot() {
        String dir;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();
        } else {
            dir = new BaseApplication().getCacheDir().getAbsolutePath();
        }
        File root = new File(dir, "nmpa");
        if (!root.exists()) {
            root.mkdirs();
        }
        return root;
    }
}

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值