首先是请求接口,获取版本号
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>
这样就完成了!