代码简介
对android 开发之前完全没有接触过,自己摸索中做的,参照了网上太多地方,就不一一列举了。
代码有点乱,主要是手生。界面就是拖点原生的组件糊上去。「Android 4.0+ 」吧,以前版本不能用。
主要功能:
1. 来去电手机归属地显示(接收系统广播实现,没有跑后台服务)
2. 手机号归属地查询,包括查询本地数据库,和通过网络查询(有道的接口,返回XML)
3. 如果网络上面的归属地信息与本地不一样,可以一键更新到本地
4. 源码里面有一个8M多的数据Sqlite数据库,27W+条手机号归属地数据,自己从网上一条一条抓取下来的,可能比我程序的价值还大些。
代码片段
// 使用网络查询归属地数据库 class RemoteHelper extends AsyncTask{ 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 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 parseXML(InputStream inputStream) throws XmlPullParserException, IOException { List products = new ArrayList (); 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); } }