首页 > 代码库 > 通过IP地址获取省份城市位置信息

通过IP地址获取省份城市位置信息

	private String mResult = null;
	private String mProvinceName;  //省份
	private String mChCityName;  //城市         
        private int GET_CITY_SUCCESS = 1;
        private int GET_CITY_FAILURE = 2;

 //Handler接收到消息进行处理,取出需要的信息
privateHandler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            if (msg.what == GET_CITY_SUCCESS) {
	//src.split("\t") 返回的是以制表符(TAB键)分隔的字符串数组
                String[] results = mResult.split("\t");
                if (results.length >= 5) {
                    mProvinceName = results[4];
                    mChCityName = results[5];
                }
                Log.i("----省份:"+mProvinceName, "----城市:"+mChCityName);
            } else if(msg.what == GET_CITY_FAILURE)
		{
                   //获取失败
		}
        };
};

 //访问新浪接口,获取ip和地理位置信息
 //返回数据格式:1 121.15.0.0121.15.215.255 中国 广东 深圳 电信
  private void getCurrentProvinceAndCity() {
        final String url = "http://int.dpool.sina.com.cn/iplookup/iplookup.php?";
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
            StatusLine statusLine =httpResponse.getStatusLine();
            if (statusLine != null && statusLine.getStatusCode() ==200) {
                mResult = EntityUtils.toString(httpResponse.getEntity()).trim();
                mHandler.sendEmptyMessage(GET_CITY_SUCCESS);
            }
        } catch (Exception e) {
            Log.d(TAG, "getCurrentProvinceAndCity, Exception");
            e.printStackTrace();
            mHandler.sendEmptyMessage(GET_CITY_FAILURE);
        }
    }