XML文件和获取XML值
XML文件样例
<?xml version="1.0" encoding="utf-8"?> <citys> <city name="CAF">中非</city> <city name="TCD">乍得</city> <city name="CHL">智利</city> <city name="CHN">中国</city> <city name="HKG">香港</city> <city name="MAC">澳门</city> <city name="TWN">台湾</city> </citys>
获取XML内容
private String getNationality(String str){ XmlResourceParser xpr = getResources().getXml(R.xml.nationality);// 找到xml文件 try { // 循环解析 while (xpr.getEventType() != XmlResourceParser.END_DOCUMENT) { if (xpr.getEventType() == XmlResourceParser.START_TAG) { String name = xpr.getName(); //获取标签名 if (name.equals("city")) { if(str.equals(xpr.getAttributeValue(null, "name"))){//获取标签里的值 return xpr.nextText();//获取标签的内容 } } } try { xpr.next(); } catch (IOException e) { e.printStackTrace(); } } } catch (XmlPullParserException | IOException e) { e.printStackTrace(); } return "null"; }
升级APK
发送请求获取输入流
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)); 安装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(); }
获取项目包名
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; }