Android解析XML文件升级APK的方法
安装APK
publicclassDownLoadApk{
publicstaticSharedPreferencessharedPrederences=null;
//启动安装界面
publicstaticvoidDownId(Contextcontext,longdownId){
DownloadManagermDownloadManager=(DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
UridownloadUri=mDownloadManager.getUriForDownloadedFile(downId);
startInstall(context,downloadUri);
}
/**
*跳转到安装界面
*@paramcontext作用域
*@paramuri包名
*/
privatestaticvoidstartInstall(Contextcontext,Uriuri){
Intentinstall=newIntent(Intent.ACTION_VIEW);
install.setDataAndType(uri,"application/vnd.android.package-archive");
install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(install);
}
//删除文件
publicstaticbooleanfileDelete(StringfilePath){
Filefile=newFile(filePath);
if(file.exists()==false){
returnfalse;
}
returnfile.delete();
}
发送请求获取输入流
Threadthread=newThread(){
@Override
publicvoidrun(){
super.run();
//XML存放在ftp服务器的地址
Stringpath=FileUtils.getDevice_address()+"News.XML";
try{
URLurl=newURL(path);
HttpURLConnectionconn=(HttpURLConnection)url
.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
//发送httpGET请求,获取相应码
if(conn.getResponseCode()==200){
InputStreamis=conn.getInputStream();
//使用pull解析器,开始解析这个流
parseNewsXml(is);
}
}catch(Exceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
}
};
thread.start();
解析XML文件
privatevoidparseNewsXml(InputStreamis){
XmlPullParserxp=Xml.newPullParser();
try{
xp.setInput(is,"utf-8");
//对节点的事件类型进行判断,就可以知道当前节点是什么节点
inttype=xp.getEventType();
Newsnews=null;
while(type!=XmlPullParser.END_DOCUMENT){
switch(type){
caseXmlPullParser.START_TAG:
if("newslist".equals(xp.getName())){
newsList=newArrayList<>();
break;
}elseif("news".equals(xp.getName())){
news=newNews();
break;
}elseif("name".equals(xp.getName())){
Stringname=xp.nextText();
news.setName(name);
break;
}elseif("code".equals(xp.getName())){
Stringcode=xp.nextText();
news.setCode(code);
break;
}
caseXmlPullParser.END_TAG:
if("news".equals(xp.getName())){
newsList.add(news);
}
break;
default:
break;
}
//解析完当前节点后,把指针移动至下一个节点,直至节点完毕,并返回它的事件类型
type=xp.next();
}
//发消息
handler.sendEmptyMessage(1);
}catch(Exceptione){
e.printStackTrace();
}
}
可以开始下载
//获取下载管理器
DownloadManagermanager=(DownloadManager)mContext.getSystemService(mContext.DOWNLOAD_SERVICE);
handler=newHandler(){
@Override
publicvoidhandleMessage(Messagemsg){
super.handleMessage(msg);
Newsnews=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.Requestdown=newDownloadManager.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();
}
}
};
跟踪下载进度
//定时任务
ScheduledExecutorServicescheduledExecutorService=Executors.newScheduledThreadPool(1);
scheduledExecutorService.scheduleAtFixedRate(newRunnable(){
@Override
publicvoidrun(){
if(isRun){
Messagemsg=mHandler.obtainMessage();
msg.what=1;
mHandler.sendMessage(msg);
}
}
},0,100,TimeUnit.MILLISECONDS);//延迟0,间隔100,单位毫秒
privateHandlermHandler=newHandler(newHandler.Callback(){
@Override
publicbooleanhandleMessage(Messagemsg){
switch(msg.what){
case1:
//android下载管理器
DownloadManager.Queryquery=newDownloadManager.Query().setFilterById(downId);
Cursorcursor=manager.query(query);
if(cursor!=null&&cursor.moveToFirst()){
//此处直接查询文件大小
longdownSize=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){
NumberFormatnumberFormat=NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
Stringresult=numberFormat.format((float)fileTotalSize/(float)downSize*100);
Log.w("打印","downloadedsize:"+result+"%");
downBtn.setText(result+"%");
}
//下载完毕
if(fileTotalSize==downSize){
isRun=false;
downBtn.setText("点击升级");
}
}
}
returntrue;
}
});
下载完毕启动安装
DownloadCompleteReceiverreceiver=newDownloadCompleteReceiver();
//下载完成后的广播
classDownloadCompleteReceiverextendsBroadcastReceiver{
@Override
publicvoidonReceive(Contextcontext,Intentintent){
if(intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)){
longdownId=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,newIntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
获取项目包名
privatestaticStringgetPackageInfo(Contextcontext){
PackageInfopi=null;
try{
PackageManagerpm=context.getPackageManager();
pi=pm.getPackageInfo(context.getPackageName(),
PackageManager.GET_CONFIGURATIONS);
returnpi.versionCode+"";
}catch(Exceptione){
e.printStackTrace();
}
returnnull;
}
总结
以上所述是小编给大家介绍的Android解析XML文件升级APK的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!