Android apk升級

看過網上很多apk升級的,但是不怎麼適合自已,所以決定自已寫一個,步驟如下:

第一步:

implementation 'com.squareup.okhttp3:okhttp:4.2.2'

第二步:新建下載apk工具類

public class ApkHttpUtil {

    private static ApkHttpUtil httpNet;
    public static ApkHttpUtil getInstance(){
        if (httpNet == null){
            httpNet = new ApkHttpUtil();
        }
        return httpNet;
    }

    
    public static void httpDownLoadApk(String url, okhttp3.Callback callback) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = client.newCall(request);
        call.enqueue(callback);

    }
}

第三步:下載apk文件

public class DownApk  {
    private static DownApk downApk;
    public static DownApk getInstance(){
        if (downApk == null){
            downApk = new DownApk();
        }
        return downApk;
    }

    //下載進度
    private static ProgressDialog progressDialog;

    /**
     * loginactivity 更新
     * @param url
     * @param context
     */
    public static void downFile(final String url, final Context context) {
        progressDialog = new ProgressDialog(context);    //進度條,在下載的時候實時更新進度,提高用戶友好度
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下載apk");
        progressDialog.setMessage("請等待安裝...");
        progressDialog.setProgress(0);
        progressDialog.setCancelable(false);//點擊返回鍵,禁止退出
        progressDialog.show();

        ApkHttpUtil.getInstance().httpDownLoadApk(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                //下載失敗
                downFial(context);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //下載。。。
                InputStream is = null;//輸入流
                FileOutputStream fos = null;//輸出流
                try {
                    is = response.body().byteStream();//獲取輸入流
                    long total = response.body().contentLength();//獲取文件大小
                    setMax(total, context);//爲progressDialog設置大小
                    File file = null;
                    if (is != null) {
                        file = new File(Environment.getExternalStorageDirectory(), "hyzx.apk");// 設置路徑
                        fos = new FileOutputStream(file);
                        byte[] buf = new byte[1024];
                        int ch = -1;
                        int process = 0;
                        while ((ch = is.read(buf)) != -1) {
                            fos.write(buf, 0, ch);
                            process += ch;
                            downLoading(process, context); 
                        }
                    }
                    fos.flush();
                    if (fos != null) {
                        fos.close();
                    }
                    sleep(1000);
                    downSuccess(context, file);
                } catch (Exception e) {
                    downFial(context);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    private static void downFial(final Context context) {
        ((LoginActivity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.cancel();
                Toast.makeText(context, "更新失敗", Toast.LENGTH_LONG).show();
            }
        });
    }

    private static void setMax(final long total, Context context) {
        ((LoginActivity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.setMax((int) total);
            }
        });
    }

    /**
     * 進度條實時更新
     *
     * @param i
     */
    private static void downLoading(final int i, Context context) {
        ((LoginActivity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressDialog.setProgress(i);
            }
        });
    }

    private static void downSuccess(final Context context, final File file) {
        //安裝
        ((LoginActivity) context).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                try {
                    sleep(1000);
                    installApk(file, context);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        });
    }

    private static void installApk(File file, Context context) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT > 23) {
            Uri apkUri = FileProvider.getUriForFile(context, "com.energy.app.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }
}

第四步:檢查更新

private final int PERMISSION_REQUEST_CODE = 1;
private final String[] permissionManifest = {
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
};
//動態申請權限
if (Build.VERSION.SDK_INT >= 23) {
    if (!permissionCheck()) {
        ActivityCompat.requestPermissions(LoginActivity.this, permissionManifest, PERMISSION_REQUEST_CODE);
        return;
    }
    checkUpdates(); //檢查更新 你的更新代碼
}
@SuppressLint("WrongConstant")
private boolean permissionCheck() {
    int permissionCheck = PackageManager.PERMISSION_GRANTED;
    String permission;
    for (int i = 0; i < permissionManifest.length; i++) {
        permission = permissionManifest[i];
        if (PermissionChecker.checkSelfPermission(LoginActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
            permissionCheck = PackageManager.PERMISSION_DENIED;
        }
    }
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        return false;
    } else {
        return true;
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == PERMISSION_REQUEST_CODE) {
        checkUpdates();
    } else {
        Toast.makeText(LoginActivity.this, "缺少必要的權限", Toast.LENGTH_LONG).show();
    }
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}

第五步:調用apk下載

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