获得用户的地理信息

来源:互联网 发布:软件测试 回归策略 编辑:程序博客网 时间:2024/04/30 07:12

一,根据IP地址获取

ip定位服务地址

发送请求,返回固定格式的字符串,解析出地址

地址格式 1-/t-1-/t-/t 中国 北京 北京 ;1-/t-1-/t-/t 中国 四川 成都

private static String ipAddress(){    HttpClient client = new DefaultHttpClient();    HttpGet httpGet = new HttpGet("http://int.dpool.sina.com.cn/iplookup/iplookup.php?qq-pf-to=pcqq.discussion");    try {            HttpResponse response = client.execute(httpGet);            if(response.getStatusLine().getStatusCode() == 200){    String result = EntityUtils.toString(response.getEntity(), "UTF-8").replace("-", "");    //String remove_ = result.replace("-", "");String[] results = result.split("\t");return results[3]+results[4]+results[5];            }        } catch (ClientProtocolException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch (IOException e) {            // TODO Auto-generated catch block            e.printStackTrace();        } catch(Exception e){            e.printStackTrace();        }    return null;}

新开一个线程执行网络操作

  new Thread(new Runnable() {        @Override        public void run() {            // TODO Auto-generated method stub            System.out.println("___"+ipAddress());        }    }).start();

二,经纬度方式

private double latitude = 0.0;private double longitude = 0.0;private void location() {    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);    LocationListener locationListener = new LocationListener() {        // Provider的状态在可用、暂时不可用和无服务三个状态直接切换时触发此函数        @Override        public void onStatusChanged(String provider, int status,                Bundle extras) {        }        // Provider被enable时触发此函数,比如GPS被打开        @Override        public void onProviderEnabled(String provider) {        }        // Provider被disable时触发此函数,比如GPS被关闭        @Override        public void onProviderDisabled(String provider) {        }        // 当坐标改变时触发此函数,如果Provider传进相同的坐标,它就不会被触发        @Override        public void onLocationChanged(Location location) {            if (location != null) {                latitude = location.getLatitude(); // 经度                longitude = location.getLongitude(); // 纬度            }        }    };    locationManager.requestLocationUpdates(            LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);    Location location = locationManager            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);    if (location != null) {        latitude = location.getLatitude(); // 经度        longitude = location.getLongitude(); // 纬度    }

需要用到的权限

  <!-- 连接互联网Internet权限 --><uses-permission android:name="android.permission.INTERNET" /><!-- GPS定位权限 --><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

参考引用

几个门户网站的IP查询接口

0 0