- // 使用网络查询归属地数据库
- class RemoteHelper extends AsyncTask<String, Void, PhoneArea> {
- public RemoteHelper(Context context) {
- }
- @Override
- protected PhoneArea doInBackground(String... params) {
- PhoneArea phoneArea = null;
- // 有道手机归属地api
- String path = "http://www.youdao.com/smartresult-xml/search.s?type=mobile&q="
- + params[0];
- try {
- HttpClient client = new DefaultHttpClient();
- HttpGet get = new HttpGet(path);
- HttpResponse response = client.execute(get);
- HttpEntity entity = response.getEntity();
- InputStream is = entity.getContent();
- if (is != null) {
- try {
- //解析XML
- List<Product> products = parseXML(is);
- if (products.size() == 1) {
- Product product = products.get(0);
- String phonenum = product.getPhonenum();
- StringBuffer location = new StringBuffer(
- product.getLocation());
- //在归属地后面加上运营商
- if (phonenum
- .matches("^(130|131|132|145|155|156|185|186).*$")) {
- location.append("[联通]");
- } else if (phonenum
- .matches("^(133|153|1349|180|181|189).*$")) {
- location.append("[电信]");
- } else {
- location.append("[移动]");
- }
- phoneArea = new PhoneArea(Integer.parseInt(phonenum
- .substring(0, 7)), location.toString()
- .replaceAll(" ", ""));
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return phoneArea;
- }
- private List<Product> parseXML(InputStream inputStream)
- throws XmlPullParserException, IOException {
- List<Product> products = new ArrayList<Product>();
- Product product = null;
- XmlPullParser parser = Xml.newPullParser();
- parser.setInput(inputStream, "GBK");
- int event = parser.getEventType();
- while (event != XmlPullParser.END_DOCUMENT) {
- switch (event) {
- case XmlPullParser.START_TAG:
- if ("product".equals(parser.getName())) {
- product = new Product();
- } else if ("phonenum".equals(parser.getName())) {
- product.setPhonenum(parser.nextText());
- } else if ("location".equals(parser.getName())) {
- product.setLocation(parser.nextText());
- }
- break;
- case XmlPullParser.END_TAG:
- if ("product".equals(parser.getName())) {
- products.add(product);
- product = null;
- }
- break;
- }
- event = parser.next();
- }
- return products;
- }
- /**
- * 返回时调用
- */
- @Override
- protected void onPostExecute(PhoneArea phoneArea) {
- if (phoneArea != null && phoneArea.getArea() != null) {
- String area = phoneArea.getArea();
- textView5.setText(area);
- //网络查询结果与本地不一致是,将「更新到本地」菜单设置为可以点击
- if (!area.equals(textView3.getText().toString())) {
- menuItem.setEnabled(true);
- }
- } else
- textView5.setText(R.string.none_area);
- progressBar2.setVisibility(ProgressBar.GONE);
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0910201410573.html
来源: http://www.codesnippet.cn/detail/0910201410573.html