一、前言
这段时间独立完成了一个项目,想把一些常用知识点记录下来,如有不足之处还请指点。望共勉之。好啦,废话不多说直接进入正题,直接上代码,效果图我就不上了,代码是小编亲测有效,大家放心好啦。
1.首先进行本地版本与服务器版本对比,这都是老套路啦(^_^)
HttpHelper.obtain().Get(Constant.UpdateUrl, null, new ICallback() {
@Override
public boolean onSucess(String result) {
updateBean = new Gson().fromJson(result, UpdateBean.class);
int versionCode = FileProvider7Utils.getVersionName(MainActivity.this);
Log.i("222", versionCode + "");
//服务器版本
int verCode = Integer.parseInt(updateBean.getVerCode());
if (verCode > versionCode) {
manager = new UpdateManager(MainActivity.this);
manager.showDialog(Constant.DownAPk + updateBean.getApkName(),updateBean.getVerDesc());
}
return false;
}
@Override
public void onFailure(String e) {
Toast.makeText(MainActivity.this, "" + e.toString(), Toast.LENGTH_SHORT).show();
}
});
2.取得版本号
public static int getVersionName(Context context)
{ int VersionName=0;
PackageManager packageManager=context.getPackageManager();
PackageInfo packageInfo;
try {
packageInfo=packageManager.getPackageInfo(context.getPackageName(),0);
VersionName=packageInfo.versionCode;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return VersionName;
}
3.UpdateManager更新类
package com.kyny.workgroup.utils;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.kyny.workgroup.R;
import com.kyny.workgroup.model.UpdateBean;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
*更新工具类
*/
public class UpdateManager {
private Dialog dialog;
private UpdateBean updateBean;
private static final String savePath = Environment
.getExternalStorageDirectory().getPath() + "/本地文件名/";
private static final String saveFileName = savePath + "xx.apk";
private ProgressBar mProgress;
private boolean interceptFlag = false;
private String loadApkUrl;
private int progress;
private static final int DOWN_UPDATE = 1;
private static final int DOWN_OVER = 2;
private Context mContext;
private Dialog downloadDialog;
private TextView tvProgress;
public UpdateManager(Context mContext) {
this.mContext = mContext;
}
private Handler mHandler=new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what)
{
case DOWN_UPDATE:
mProgress.setProgress(progress);
tvProgress.setText(progress+"%");
break;
case DOWN_OVER:
installApk();
break;
}
}
};
/**
* 安装apk
*/
private void installApk() {
File apkfile = new File(saveFileName);
if (!apkfile.exists()) {
return;
}
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
// Uri uriForFile = FileProvider7Utils.getUriForFile(mContext, apkfile);
FileProvider7Utils.setIntentDataAndType(mContext,intent,
"application/vnd.android.package-archive",apkfile,true);
// intent.setDataAndType(uriForFile,
// "application/vnd.android.package-archive");
mContext.startActivity(intent);
downloadDialog.dismiss();
}
//升级对话框
public void showDialog(final String downApkUrl,String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("版本升级").
setIcon(R.mipmap.phone_icon). // 设置提示框的图标
setMessage("发现新版本+\n"+message).// 设置要显示的信息
setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
@Override
public void onClick(DialogInterface dialog, int which) {
startUpload(downApkUrl);//下载最新的版本程序
}
}).setNegativeButton("取消", null);//设置取消按钮,null是什么都不做,并关闭对话框
AlertDialog alertDialog = builder.create();
// 显示对话框
alertDialog.show();
}
private void startUpload(String downApkUrl)
{
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("文件下载");
final LayoutInflater inflater = LayoutInflater.from(mContext);
View v = inflater.inflate(R.layout.progress, null);
mProgress = (ProgressBar) v.findViewById(R.id.progress);
tvProgress = (TextView) v.findViewById(R.id.tv_progress);
builder.setView(v);
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
interceptFlag = true;
}
});
downloadDialog = builder.create();
downloadDialog.show();
loadApkUrl = downApkUrl;
DownApk();
}
//这里我是用的子线程,这里大家根据自己需要
public void DownApk()
{
Thread thread=new Thread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL(loadApkUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
int length = conn.getContentLength();
InputStream is = conn.getInputStream();
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
String apkFile = saveFileName;
File ApkFile = new File(apkFile);
FileOutputStream fos = new FileOutputStream(ApkFile);
int count = 0;
byte buf[] = new byte[1024];
do {
int numread = is.read(buf);
count += numread;
progress = (int) (((float) count / length) * 100);
// 更新进度
mHandler.sendEmptyMessage(DOWN_UPDATE);
if (numread <= 0) {
// 下载完成通知安装
mHandler.sendEmptyMessage(DOWN_OVER);
break;
}
fos.write(buf, 0, numread);
} while (!interceptFlag);// 点击取消就停止下载.
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread.start();
}
}
4.progress.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<ProgressBar
android:id="@+id/progress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
/>
<TextView
android:id="@+id/tv_progress"
android:layout_width="match_parent"
android:gravity="right"
android:text="0%"
android:layout_height="wrap_content" />
</LinearLayout>
/**
* android7.0 安装Apk 必须要加临时权限
* @param context
* @param intent
* @param type
* @param file
* @param writeAble 是读还是写,一般安装都是以读形式,默认为true
*/
public static void setIntentDataAndType(Context context,
Intent intent,
String type,
File file,
boolean writeAble) {
if (Build.VERSION.SDK_INT >= 24) {
intent.setDataAndType(getUriForFile(context, file), type);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (writeAble) {
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
}
} else {
intent.setDataAndType(Uri.fromFile(file), type);
}
end:注意:8.0机型如发现无法安装,请在manifest添加
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />