如何在Android中解析XML文件
这篇文章给大家介绍如何在Android中解析XML文件,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
成都创新互联公司专注于江北企业网站建设,成都响应式网站建设公司,商城开发。江北网站建设公司,为江北等地区提供建站服务。全流程按需网站设计,专业设计,全程项目跟踪,成都创新互联公司专业和态度为您提供的服务
安装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是什么
Android是一种基于Linux内核的自由及开放源代码的操作系统,主要使用于移动设备,如智能手机和平板电脑,由美国Google公司和开放手机联盟领导及开发。
关于如何在Android中解析XML文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
网页题目:如何在Android中解析XML文件
文章出自:http://cdiso.cn/article/jdjsph.html