UpdateChecker.java 6.81 KB
package com.hjx.personalcenter.update;

/**
 * Created by l on 2017/7/17.
 */

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.ResultReceiver;
import android.support.v4.app.FragmentActivity;
import android.view.View;

import com.hjx.personalcenter.http.HttpCode;
import com.hjx.personalcenter.http.HttpManager;
import com.hjx.personalcenter.model.AppVersion;
import com.mylhyl.circledialog.CircleDialog;

import java.io.File;

public class UpdateChecker{
    private static final String TAG = "UpdateChecker";
    private Context mContext;
    //检查版本信息的线程
    private Thread mThread;

    private AppVersion mAppVersion;
    //下载apk的对话框
    private ProgressDialog mProgressDialog;

    private File apkFile;


    public UpdateChecker(Context context) {
        mContext = context;
        // instantiate it within the onCreate method
        mProgressDialog = new ProgressDialog(context);
        mProgressDialog.setMessage("正在下载");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(true);
        mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

            }
        });
        mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                // TODO Auto-generated method stub

            }
        });
    }

    public void checkForUpdates() {

        final  Handler handler = new Handler(){
            public void handleMessage(Message msg) {
                if (msg.what == HttpCode.APPUPDATE_SUCESS) {
                    mAppVersion = (AppVersion) msg.obj;
                    try{
                        int versionCode = mContext.getPackageManager().getPackageInfo(mContext.getPackageName(), 0).versionCode;
                        if (mAppVersion.getVersioncode() > versionCode) {
                            if(mAppVersion.isEncrypted()){
                                showForceUpdateDialog();
                            }else{
                                showUpdateDialog();
                            }
                        } else {
                            //Toast.makeText(mContext, "已经是最新版本", Toast.LENGTH_SHORT).show();
                        }
                    }catch (PackageManager.NameNotFoundException ignored) {
                        //
                    }
                }
            }
        };

        mThread = new Thread() {
            @Override
            public void run() {
                try {
                    HttpManager.getInstance().updateAPP(mContext,"com.hjx.personalcenter","呼叫老师安卓Pad",handler);
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
        };
        mThread.start();
    }

    private void showForceUpdateDialog() {
        new CircleDialog.Builder((FragmentActivity)mContext)
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setWidth(0.5f)
                .setTitle("升级提示")
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((Activity)mContext).finish();

                    }
                })
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        downLoadApk();
                    }
                })
                .show();
    }

    private void showUpdateDialog() {
        new CircleDialog.Builder((FragmentActivity)mContext)
                .setCanceledOnTouchOutside(false)
                .setCancelable(false)
                .setWidth(0.5f)
                .setTitle("升级提示")
                .setNegative("取消", null)
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        downLoadApk();
                    }
                })
                .show();
    }

    private void downLoadApk() {
        String apkUrl = mAppVersion.getUrl();
        String dir = mContext.getExternalFilesDir( "apk").getAbsolutePath();
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        if(folder.exists() && folder.isDirectory()) {
            //do nothing
        }else {
            folder.mkdirs();
        }
        String filename = apkUrl.substring(apkUrl.lastIndexOf("/"),apkUrl.length());
        String destinationFilePath =  dir + "/" + filename;
        apkFile = new File(destinationFilePath);
        if(mAppVersion.isEncrypted()){
            mProgressDialog.setCancelable(false);
        }
        mProgressDialog.show();
        Intent intent = new Intent(mContext, DownloadService.class);
        intent.putExtra("url", apkUrl);
        intent.putExtra("dest", destinationFilePath);
        intent.putExtra("receiver", new DownloadReceiver(new Handler()));
        mContext.startService(intent);
    }

    private class DownloadReceiver extends ResultReceiver{
        public DownloadReceiver(Handler handler) {
            super(handler);
        }
        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {
            super.onReceiveResult(resultCode, resultData);
            if (resultCode == DownloadService.UPDATE_PROGRESS) {
                int progress = resultData.getInt("progress");
                mProgressDialog.setProgress(progress);
                if (progress == 100) {
                    mProgressDialog.dismiss();
                    //如果没有设置SDCard写权限,或者没有sdcard,apk文件保存在内存中,需要授予权限才能安装
                    String[] command = {"chmod","777",apkFile.toString()};
                    try{
                        ProcessBuilder builder = new ProcessBuilder(command);
                        builder.start();
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
                        mContext.startActivity(intent);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}