更新Apk完整版

首先是請求接口,獲取版本號

Integer.parseInt(App.getVersionCode())

當需要更新的時候

//Apk下載的方法
private void responseVersionData(final VersionInfo.Version data) {
    if (data.getVersionNo() > Integer.parseInt(App.getVersionCode())) {
        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(LogoActivity.this, R.style.newPassword);
        builder.setCancelable(false);// 設置點擊屏幕Dialog不消失
        View inflate = getLayoutInflater().inflate(R.layout.upgrade_layout, null);
        AutoUtils.setSize(LogoActivity.this, false, 720, 1280);
        AutoUtils.auto(inflate);
        final TextView confirmupgrade = (TextView) inflate.findViewById(R.id.confirm_upgrade);//更新按鈕
        final TextView updatecontent = (TextView) inflate.findViewById(R.id.update_content);
        final ProgressBar progressBar = (ProgressBar) inflate.findViewById(R.id.progress_xiazai);
        final TextView anzhuang = (TextView) inflate.findViewById(R.id.anzhuang);
        final View xian = (View) inflate.findViewById(R.id.xian);
        final TextView colse = (TextView) inflate.findViewById(R.id.close);
        builder.setCancelable(false);// 設置點擊屏幕Dialog不消失
        if (data.getForce() == 1) {
            colse.setVisibility(View.GONE);
        }
        String content = data.getContent();
        if (!TextUtils.isEmpty(content)) {
            updatecontent.setText(content);
        }


        builder.setView(inflate);
        final android.support.v7.app.AlertDialog dialog = builder.create();
        dialog.show();
        colse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                getGuangGao();
            }
        });
        confirmupgrade.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT >= 23) {
                    File apkFile = Environment.getExternalStorageDirectory();
                    //刪除之前安裝包
                    File apkFile2 = new File(apkFile, "/gc.apk");
                    if (apkFile2.exists()) {
                        apkFile2.delete();
                    }
                    progressBar.setVisibility(View.VISIBLE);
                    colse.setVisibility(View.GONE);
                    confirmupgrade.setEnabled(false);
                    confirmupgrade.setText("0%");
                    xian.setVisibility(View.GONE);
                    DownLoadApkUtils.DownLoadFile(apkFile.getAbsolutePath(),
                            "gc.apk",
                            data.getVersionUrl(),
                            LogoActivity.this,
                            progressBar,
                            confirmupgrade,
                            colse,
                            dialog,
                            data.getForce(),
                            0,
                            xian, anzhuang);
                }
            }
        });
    } else {
        init();
    }
}

PassWord樣式:

<style name="newPassword" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
</style>

下面是更新的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="700.0px"
    android:layout_marginLeft="48.0px"
    android:layout_marginRight="48.0px"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="700.0px"
        android:background="@mipmap/gengxintixingone">

        <TextView
            android:id="@+id/update_content"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="100.0px"
            android:layout_marginTop="400.0px"
            android:lineSpacingMultiplier="1.2"
            android:textColor="@color/colortextcolor"
            android:textSize="36.0px" />

        <ProgressBar
            android:id="@+id/progress_xiazai"
            style="?android:progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="10.0px"
            android:layout_above="@+id/relative"
            android:layout_marginLeft="40.0px"
            android:layout_marginRight="40.0px"
            android:layout_marginBottom="10.0px"
            android:max="100"
            android:progressDrawable="@drawable/progress_style"
            android:visibility="gone" />

        <RelativeLayout
            android:id="@+id/relative"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentBottom="true">

            <TextView
                android:id="@+id/anzhuang"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:paddingTop="40.0px"
                android:paddingBottom="40.0px"
                android:text="立即安裝"
                android:textColor="#ff137bf1"
                android:textSize="36.0px"
                android:visibility="gone" />

            <LinearLayout
                android:id="@+id/back_dialog"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <TextView
                    android:id="@+id/close"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.0"
                    android:gravity="center"
                    android:paddingTop="40.0px"
                    android:paddingBottom="40.0px"
                    android:text="殘忍拒絕"
                    android:textSize="36.0px" />

                <View
                    android:id="@+id/xian"
                    android:layout_width="1.0px"
                    android:layout_height="match_parent"
                    android:background="@color/colorback" />

                <TextView
                    android:id="@+id/confirm_upgrade"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_weight="1.0"
                    android:gravity="center"
                    android:paddingTop="40.0px"
                    android:paddingBottom="40.0px"
                    android:text="立即升級"
                    android:textColor="@color/colorblue"
                    android:textSize="36.0px" />
            </LinearLayout>
        </RelativeLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1.0px"
            android:layout_above="@+id/relative"
            android:background="@color/colorback" />
    </RelativeLayout>
</LinearLayout>

下載Apk的工具類:

public class DownLoadApkUtils {

    //  compile 'com.zhy:okhttputils:2.0.0'   添加這個框架


    private DisplayMetrics metrics;
    private int screen_width;
    private int screen_height;


    /**
     * 下載文件
     *
     * @param
     * @param path        保存路徑
     * @param fileName    文件名字
     * @param url         下載地址
     * @param mContext    上下文
     * @param progressBar
     * @param dialog
     * @param force
     * @param type
     * @param xian
     * @param anzhuang
     */
    public static void DownLoadFile(String path, String fileName, String url, final Activity mContext, final ProgressBar progressBar, final TextView confirmupgrade, final TextView colse, final android.support.v7.app.AlertDialog dialog, final int force, final int type, View xian, final TextView anzhuang) {
//        final ProgressDialog pd;    //進度條對話框
//        pd = new ProgressDialog(mContext);
//        pd.setCancelable(false);// 設置點擊屏幕Dialog不消失
//        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        pd.setMessage("正在下載更新");
//        pd.setMax(100);
//        pd.show();

        OkHttpUtils
                .get()
                .url(url)
                .build()
                .execute(new FileCallBack(path, fileName) {
                    @Override
                    public void inProgress(float progress) {
                        progressBar.setProgress((int) (progress * 100));
                        confirmupgrade.setText((int) (progress * 100) + "%");
                    }

                    @Override
                    public void onError(Request request, Exception e) {
//                        Log.e(TAG, "onError :" + e.getMessage());
                        progressBar.setProgress(0);
                        progressBar.setVisibility(View.GONE);
                        confirmupgrade.setText("立即升級");
                        confirmupgrade.setEnabled(true);
                        if (force != 1) {
                            colse.setVisibility(View.VISIBLE);
                        }
                        ToastUtil.getInstance().toastCentent("網絡較差,下載失敗");
                    }

                    @Override
                    public void onResponse(final File file) {
//                        Log.e(TAG, "onResponse :" + file.getAbsolutePath());
                        ToastUtil.getInstance().toastCentent("下載完成");
                        confirmupgrade.setVisibility(View.GONE);
                        anzhuang.setVisibility(View.VISIBLE);
                        anzhuang.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                DownLoadApk downLoadApk = new DownLoadApk(mContext);
                                downLoadApk.installApk(file, mContext);
                            }
                        });
                        if (type == 2) {
                            DownLoadApk downLoadApk = new DownLoadApk(mContext);
                            downLoadApk.installApk(file, mContext);
                            dialog.dismiss();
                        }

                    }
                });

    }

    /**
     * 獲取屏幕的寬
     *
     * @param mContext
     */
    public static int getDisplayWidth(Context mContext) {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getWidth();
    }

    /**
     * 獲取屏幕的高
     *
     * @param mContext
     */
    public static int getDisplayHeight(Context mContext) {
        WindowManager wm = (WindowManager) mContext
                .getSystemService(Context.WINDOW_SERVICE);
        return wm.getDefaultDisplay().getHeight();
    }
}

然後是安裝Apk的工具類:

public class DownLoadApk {

    public Context context;
    private boolean haveInstallPermission;

    public DownLoadApk(Context context) {
        this.context = context;
    }

    /*
     * 從服務器中下載APK
     */
    public void downLoadApk(final VersionInfo.Version versionInfo) {
        final ProgressDialog pd;    //進度條對話框
        pd = new ProgressDialog(context);
        pd.setCancelable(false);// 設置點擊屏幕Dialog不消失
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下載更新");
        pd.show();
        new Thread() {
            @Override
            public void run() {
                try {
                    File file = getFileFromServer(versionInfo.getVersionUrl(), pd);

                    installApk(file, context);
                    pd.dismiss(); //結束掉進度條對話框

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    /**
     * 下載方法
     *
     * @param path
     * @param pd
     * @return
     * @throws Exception
     */
    public File getFileFromServer(String path, ProgressDialog pd)
            throws Exception {
        // 如果相等的話表示當前的sdcard掛載在手機上並且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            // 獲取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(),
                    "gc.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                total += len;
                // 獲取當前下載量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }

    /**
     * 安裝Apk
     *
     * @param file
     * @param context
     */
    public void installApk(File file, Context context) {

        Intent installIntent = new Intent(Intent.ACTION_VIEW);
        installIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        if (Build.VERSION.SDK_INT >= 24) { //判讀版本是否在7.0以上
            //參數1 上下文, 參數2 Provider主機地址 和清單文件中保持一致   參數3  共享的文件
            Uri apkUri = FileProvider.getUriForFile(context, "你的applicationId.provider", file);
            //添加這一句表示對目標應用臨時授權該Uri所代表的文件
            installIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            installIntent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            //兼容8.0( 8.0 後需要加 未知來源的手動獲取權限 來調起安裝頁面)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                boolean hasInstallPermission = context.getPackageManager().canRequestPackageInstalls();
                if (!hasInstallPermission) {
                    startInstallPermissionSettingActivity(context);
                    return;
                }
            }
        } else {
            installIntent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(installIntent);


    }

    /**
     * 跳轉到設置-允許安裝未知來源-頁面
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private void startInstallPermissionSettingActivity(final Context context) {
        //注意這個是8.0新API
        Uri packageURI = Uri.parse("package:" + context.getPackageName());
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

還需要在清單文件中創建一個provider:

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

這樣就完成了!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章