思路:1在服务器固定目录存放固定的了版本文件;
2.应用请求服务器端的版本文件,判断是否有最新版本;
3.创建下载连接,下载最新apk;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Xml;
/**
* Created by shijian on 15-8-13.
* 检查应用版本
*/
public class CheckVersionUtil {
public void checkVersion(Context context) {
this.context = context;
threadPool.execute(checkVersion);
}
/**
* 检查版本线程
* @author shijian
*/
Runnable checkVersion = new Runnable() {
@Override
public void run() {
try {
//从清单文件中获得当前版本号
PackageInfo info = context.getPackageManager().getPackageInfo("cn.com.shijian.test", 0);
float localVersion = Float.valueOf(info.versionName);
float serverVersion = 0;
//版本文件在服务器上的路径
String versionPath = CommonUtil.prefixUrl + File.separator + context.getString(R.string.apkversionUrl);
URL url = new URL(versionPath);
HttpURLConnection conn= (HttpURLConnection)url.openConnection();
//读入XML文件输入流
InputStream input = conn.getInputStream();
//解析XML文件
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(input, "utf-8");
int eventType = parser.getEventType();
while(eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_TAG:
//版本
if ("version".equals(parser.getName())) {
serverVersion = Float.valueOf(parser.nextText());
}
//是否强制更新
if("ismustupdate".equals(parser.getName())){
ismustupdate = parser.nextText();
}
if ("description".equals(parser.getName())) {
//换行
description = parser.nextText().replace("\\n", "\n");
}
break;
}
eventType = parser.next();
}
//如果服务器版本号大于本地版本号
if (serverVersion > localVersion) {
boolean post = handler.post(new Runnable() {
@Override
public void run() {
Builder builder = new Builder(context);
builder.setTitle("版本升级");
builder.setMessage(description);
builder.setPositiveButton("下载最新版", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
downloadApk();
}
});
if ("1".equals(ismustupdate)) {
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
AlertDialog dialog = builder.create();
dialog.show();
}
});
//当前版本是最新版
} else if (serverVersion <= localVersion) {
if (context.getClass().equals(HomeActivity.class)) {
return;
}
handler.post( new Runnable() {
public void run() {
AlertDialog.Builder builder = new Builder(context);
builder.setTitle("版本升级");
builder.setMessage("已经是最新版本");
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
} catch (XmlPullParserException e) {
e.printStackTrace();
}
} catch (NameNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
threadPool.shutdown();
}
}
};
/**
*
* 点击下载apk
* @author shijian
* @since 2015-8-13
*/
public void downloadApk() {
//获得DownloadManager
final DownloadManager downloadMgr = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
//定义下载URI
Uri apkLocation = Uri.parse(CommonUtil.prefixUrl + File.separator + context.getString(R.string.apkUrl));
Request request = new Request(apkLocation);
//request.setAllowedNetworkTypes(Request.NETWORK_WIFI);
request.setTitle("e车问更新");
//如果文件件不存在则建立
File folder = Environment.getExternalStoragePublicDirectory("echewen");
if (folder.exists() && folder.isDirectory()){
} else {
folder.mkdirs();
}
//如果echewen.apk已经存在删除掉,防止出现多个
File apk = new File(CheckVersionUtil.APK_UPDATE);
if (apk.exists()) {
apk.delete();
}
//保存下载的文件到指定目录下
request.setDestinationInExternalPublicDir("echewen", "echewen.apk");
//该downloadmanager的ID
final long ref = downloadMgr.enqueue(request);
IntentFilter filter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
long mRef = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if (mRef == ref) {
Cursor c = downloadMgr.query(new DownloadManager.Query().setFilterById(mRef));
c.moveToFirst();
String downloadFile = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
installIntent.setDataAndType(Uri.parse(downloadFile),
"application/vnd.android.package-archive");//设置intent的数据类型
context.startActivity(installIntent);
}
}
};
context.registerReceiver(receiver, filter);
}
//线程池
ExecutorService threadPool = Executors.newCachedThreadPool();
Handler handler = new Handler();
//版本升级说明
String description;
//上下文
Context context;
String ismustupdate = "0";//0:必须更新;1:不必须
public static final String APK_UPDATE = Environment.getExternalStorageDirectory().getPath() + "/echewen/echewen.apk";
public static final String STORAGE_IMAGE_PATH = Environment.getExternalStorageDirectory().getPath() + "/echewen/apk/";
}
转载于:https://blog.51cto.com/3504199/1684292