Android解析XML文件升级APK的方法
作者:xi阳 时间:2022-06-05 20:47:26
安装APK
public class DownLoadApk {
public static SharedPreferences sharedPrederences = null;
//启动安装界面
public static void DownId(Context context, long downId){
DownloadManager mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri downloadUri = mDownloadManager.getUriForDownloadedFile(downId);
startInstall(context, downloadUri);
}
/**
* 跳转到安装界面
* @param context 作用域
* @param uri 包名
*/
private static void startInstall(Context context, Uri uri) {
Intent install = new Intent(Intent.ACTION_VIEW);
install.setDataAndType(uri, "application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
//删除文件
public static boolean fileDelete(String filePath) {
File file = new File(filePath);
if (file.exists() == false) {
return false;
}
return file.delete();
}
发送请求获取输入流
Thread thread = new Thread() {
@Override
public void run() {
super.run();
//XML存放在ftp服务器的地址
String path = FileUtils.getDevice_address()+"News.XML";
try {
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//发送http GET请求,获取相应码
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
//使用pull解析器,开始解析这个流
parseNewsXml(is);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread.start();
解析XML文件
private void parseNewsXml(InputStream is) {
XmlPullParser xp = Xml.newPullParser();
try {
xp.setInput(is, "utf-8");
//对节点的事件类型进行判断,就可以知道当前节点是什么节点
int type = xp.getEventType();
News news = null;
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("newslist".equals(xp.getName())) {
newsList = new ArrayList<>();
break;
} else if ("news".equals(xp.getName())) {
news = new News();
break;
} else if ("name".equals(xp.getName())) {
String name = xp.nextText();
news.setName(name);
break;
} else if ("code".equals(xp.getName())) {
String code = xp.nextText();
news.setCode(code);
break;
}
case XmlPullParser.END_TAG:
if ("news".equals(xp.getName())) {
newsList.add(news);
}
break;
default:
break;
}
//解析完当前节点后,把指针移动至下一个节点,直至节点完毕,并返回它的事件类型
type = xp.next();
}
// 发消息
handler.sendEmptyMessage(1);
} catch (Exception e) {
e.printStackTrace();
}
}
可以开始下载
//获取下载管理器
DownloadManager manager =(DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
News news = newsList.get(0);
Log.i("aii", "XML: "+news.getCode()+",apk:"+getPackageInfo(mContext));
if(Integer.valueOf(news.getCode())>Integer.valueOf(getPackageInfo(mContext))){
if(dowmCliek) {
//开启进度条线程
isRun = true;
dowmCliek = false;
//更新APK前删除原来的安装包
DownLoadApk.fileDelete(path + "/" + mAPK);
//创建下载请求
DownloadManager.Request down = new DownloadManager.Request(
Uri.parse(mWebsite));
//设置允许使用的网络类型,这里是移动网络和wifi都可以
down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
//禁止发出通知,既后台下载
down.setShowRunningNotification(true);
//不显示下载界面
down.setVisibleInDownloadsUi(true);
//标题
down.setDestinationInExternalFilesDir(mContext, null, "XXX升级中...");
//将下载请求放入队列,返回下载id
downId = manager.enqueue(down);
}else{
Toast.makeText(mContext,"升级中...",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(mContext,"已是最新版本无需升级...",Toast.LENGTH_SHORT).show();
}
}
};
跟踪下载进度
//定时任务
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
if(isRun) {
Message msg = mHandler.obtainMessage();
msg.what = 1;
mHandler.sendMessage(msg);
}
}
}, 0, 100, TimeUnit.MILLISECONDS);//延迟0,间隔100,单位毫秒
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 1:
//android下载管理器
DownloadManager.Query query = new DownloadManager.Query().setFilterById(downId);
Cursor cursor = manager.query(query);
if (cursor != null && cursor.moveToFirst()) {
//此处直接查询文件大小
long downSize = cursor.getLong(cursor.getColumnIndex(
DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
//获取文件下载总大小
fileTotalSize =cursor.getLong(cursor.getColumnIndex(
DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
cursor.close();
Log.w("打印", "总大小" + downSize);
Log.w("打印", "下载进度 " + fileTotalSize);
if (fileTotalSize>0) {
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
String result = numberFormat.format((float)fileTotalSize/(float)downSize*100);
Log.w("打印", "downloaded size: " + result+"%");
downBtn.setText(result+"%");
}
//下载完毕
if(fileTotalSize==downSize) {
isRun = false;
downBtn.setText("点击升级");
}
}
}
return true;
}
});
下载完毕启动安装
DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();
//下载完成后的广播
class DownloadCompleteReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
if(downId!=-1) {
//启动安装
DownLoadApk.DownId(context,downId);
dowmCliek=true;
}
}else{
Toast.makeText(context, intent.getAction()+"下载失败", Toast.LENGTH_SHORT).show();
}
}
}
//启动下载完成广播
mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
获取项目包名
private static String getPackageInfo(Context context) {
PackageInfo pi = null;
try {
PackageManager pm = context.getPackageManager();
pi = pm.getPackageInfo(context.getPackageName(),
PackageManager.GET_CONFIGURATIONS);
return pi.versionCode+"";
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
总结
以上所述是小编给大家介绍的Android解析XML文件升级APK的方法网站的支持!
来源:https://www.cnblogs.com/94xiyang/archive/2018/07/30/9389881.html
标签:android,xml,apk
0
投稿
猜你喜欢
Springboot如何使用mybatis实现拦截SQL分页
2021-08-15 13:16:56
Java实现简单GUI登录和注册界面
2022-09-02 06:36:21
C# Winform下载文件并显示进度条的实现代码
2022-11-26 04:39:02
C#基于Socket套接字的网络通信封装
2023-11-08 16:42:18
Android中asset文件夹与raw文件夹的区别深入解析
2022-11-22 01:40:34
MyBatis中的模糊查询语句
2022-09-30 03:36:59
Java模拟多线程实现抢票代码实例
2022-11-17 07:41:51
IDEA快速搭建spring boot项目教程(Spring initializr)
2023-08-17 21:11:16
关于C#理解装箱与拆箱
2023-06-18 21:07:50
Java 容器类源码详解 Set
2022-03-21 18:08:40
Java中的阻塞队列详细介绍
2023-12-14 15:00:49
springboot之如何获取项目目录路径
2022-08-09 21:44:17
Android 调用发送短信的方法
2023-05-30 22:56:40
详解flutter中常用的container layout实例
2022-07-25 07:49:53
Android webview和js互相调用实现方法
2022-06-03 13:11:59
android编程实现添加文本内容到sqlite表中的方法
2023-07-09 06:59:13
Java中ArrayList集合的常用方法大全
2023-09-01 15:23:30
详解java中BigDecimal精度问题
2021-08-17 10:24:59
Android中文件的压缩和解压缩实例代码
2022-06-25 12:06:29
如何使用正则表达式判断邮箱(以C#为例)
2022-12-09 21:38:30