這篇文章給大家介紹如何在Android中解析XML文件,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。
成都創(chuàng)新互聯(lián)公司專注于江北企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城開(kāi)發(fā)。江北網(wǎng)站建設(shè)公司,為江北等地區(qū)提供建站服務(wù)。全流程按需網(wǎng)站設(shè)計(jì),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,成都創(chuàng)新互聯(lián)公司專業(yè)和態(tài)度為您提供的服務(wù)
安裝APK
public class DownLoadApk { public static SharedPreferences sharedPrederences = null; //啟動(dòng)安裝界面 public static void DownId(Context context, long downId){ DownloadManager mDownloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE); Uri downloadUri = mDownloadManager.getUriForDownloadedFile(downId); startInstall(context, downloadUri); } /** * 跳轉(zhuǎn)到安裝界面 * @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(); }
發(fā)送請(qǐng)求獲取輸入流
Thread thread = new Thread() { @Override public void run() { super.run(); //XML存放在ftp服務(wù)器的地址 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); //發(fā)送http GET請(qǐng)求,獲取相應(yīng)碼 if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); //使用pull解析器,開(kāi)始解析這個(gè)流 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"); //對(duì)節(jié)點(diǎn)的事件類型進(jìn)行判斷,就可以知道當(dāng)前節(jié)點(diǎn)是什么節(jié)點(diǎn) 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; } //解析完當(dāng)前節(jié)點(diǎn)后,把指針移動(dòng)至下一個(gè)節(jié)點(diǎn),直至節(jié)點(diǎn)完畢,并返回它的事件類型 type = xp.next(); } // 發(fā)消息 handler.sendEmptyMessage(1); } catch (Exception e) { e.printStackTrace(); } }
可以開(kāi)始下載
//獲取下載管理器 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) { //開(kāi)啟進(jìn)度條線程 isRun = true; dowmCliek = false; //更新APK前刪除原來(lái)的安裝包 DownLoadApk.fileDelete(path + "/" + mAPK); //創(chuàng)建下載請(qǐng)求 DownloadManager.Request down = new DownloadManager.Request( Uri.parse(mWebsite)); //設(shè)置允許使用的網(wǎng)絡(luò)類型,這里是移動(dòng)網(wǎng)絡(luò)和wifi都可以 down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI); //禁止發(fā)出通知,既后臺(tái)下載 down.setShowRunningNotification(true); //不顯示下載界面 down.setVisibleInDownloadsUi(true); //標(biāo)題 down.setDestinationInExternalFilesDir(mContext, null, "XXX升級(jí)中..."); //將下載請(qǐng)求放入隊(duì)列,返回下載id downId = manager.enqueue(down); }else{ Toast.makeText(mContext,"升級(jí)中...",Toast.LENGTH_SHORT).show(); } }else{ Toast.makeText(mContext,"已是最新版本無(wú)需升級(jí)...",Toast.LENGTH_SHORT).show(); } } };
跟蹤下載進(jìn)度
//定時(shí)任務(wù) 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("打印", "下載進(jìn)度 " + 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("點(diǎn)擊升級(jí)"); } } } return true; } });
下載完畢啟動(dòng)安裝
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) { //啟動(dòng)安裝 DownLoadApk.DownId(context,downId); dowmCliek=true; } }else{ Toast.makeText(context, intent.getAction()+"下載失敗", Toast.LENGTH_SHORT).show(); } } } //啟動(dòng)下載完成廣播 mContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
獲取項(xiàng)目包名
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是一種基于Linux內(nèi)核的自由及開(kāi)放源代碼的操作系統(tǒng),主要使用于移動(dòng)設(shè)備,如智能手機(jī)和平板電腦,由美國(guó)Google公司和開(kāi)放手機(jī)聯(lián)盟領(lǐng)導(dǎo)及開(kāi)發(fā)。
關(guān)于如何在Android中解析XML文件就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。