android定位的几种方式

来源:互联网 发布:mysql 主从备份 主键 编辑:程序博客网 时间:2024/05/20 15:39

转自:http://m.blog.csdn.net/article/details?id=44179013

android 定位一般有四种方法,这四种方式分别是:GPS定位,WIFI定准,基站定位,AGPS定位,
                             
(1)Android GPS:需要GPS硬件支持,直接和卫星交互来获取当前经纬度,这种方式需要手机支持GPS模块(现在大部分的智能机应该都有了)。通过GPS方式准确度是最高的,但是它的缺点也非常明显:1,比较耗电;2,绝大部分用户默认不开启GPS模块;3,从GPS模块启动到获取第一次定位数据,可能需要比较长的时间;4,室内几乎无法使用。这其中,缺点2,3都是比较致命的。需要指出的是,GPS走的是卫星通信的通道,在没有网络连接的情况下也能用。
                             
要实用Adnroid平台的GPS设备,首先需要添加上权限,所以需要添加如下权限:  
                             

?
1
uses-permission android:name= android.permission.ACCESS_FINE_LOCATION  /uses-permission

具体实现代码如下:

首先判断GPS模块是否存在或者是开启:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
private voidopenGPSSettings() {
            LocationManager alm = (LocationManager)this
               .getSystemService(Context.LOCATION_SERVICE);
            if(alm
               .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
              Toast.makeText(this, GPS模块正常 ,Toast.LENGTH_SHORT)
                  .show();
              return;
            }
            Toast.makeText(this, 请开启GPS! ,Toast.LENGTH_SHORT).show();
            Intent intent = newIntent(Settings.ACTION_SECURITY_SETTINGS);
           startActivityForResult(intent,0);//此为设置完成后返回到获取界面
          }

如果开启正常,则会直接进入到显示页面,如果开启不正常,则会进行到GPS设置页面:
                            
获取代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private voidgetLocation()
          {
            // 获取位置管理服务
            LocationManager locationManager;
            String serviceName = Context.LOCATION_SERVICE;
            locationManager = (LocationManager)this.getSystemService(serviceName);
            // 查找到服务信息
            Criteria criteria =new Criteria();
           criteria.setAccuracy(Criteria.ACCURACY_FINE);// 高精度
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
           criteria.setPowerRequirement(Criteria.POWER_LOW);// 低功耗
            String provider =locationManager.getBestProvider(criteria,true); // 获取GPS信息
            Location location =locationManager.getLastKnownLocation(provider);// 通过GPS获取位置
            updateToNewLocation(location);
            // 设置监听*器,自动更新的最小时间为间隔N秒(1秒为1*1000,这样写主要为了方便)或最小位移变化超过N米
            locationManager.requestLocationUpdates(provider,1001000,500,
                locationListener);  }

 到这里就可以获取到地理位置信息了,但是还是要显示出来,那么就用下面的方法进行显示:
                           
代码

?
1
2
3
4
5
6
7
8
9
10
11
private voidupdateToNewLocation(Location location) {
            TextView tv1;
            tv1 = (TextView)this.findViewById(R.id.tv1);
            if(location != null) {
              doublelatitude = location.getLatitude();
              doublelongitude=location.getLongitude();
              tv1.setText( 维度: + latitude+ \n经度 +longitude);
            }else {
              tv1.setText( 无法获取地理信息 );
            }
          }

(2)Android 基站定位:Android 基站定位只要明白了基站/WIFI定位的原理,自己实现基站/WIFI定位其实不难。基站定位一般有几种,第一种是利用手机附近的三个基站进行三角定位,由于每个基站的位置是固定的,利用电磁波在这三个基站间中转所需要时间来算出手机所在的坐标;第二种则是利用获取最近的基站的信息,其中包括基站 id,location area code、mobile country code、mobile network code和信号强度,将这些数据发送到google的定位web服务里,就能拿到当前所在的位置信息,误差一般在几十米到几百米之内。其中信号强度这个数据很重要,
                            
               这里笔者就不多做解释了,直接给出一个文章,这个文章写的非常好,
                            
               http://www.jb51.net/article/34522.htm
                             
(3)Android Wifi定位:根据一个固定的WifiMAC地址,通过收集到的该Wifi热点的位置,然后访问网络上的定位服务以获得经纬度坐标。因为它和基站定位其实都需要使用网络,所以在Android也统称为Network方式。


WiFi定位的原理

具体来说,WiFi能够定位,原理是这样的:

1、每一个无线AP(路由器)都有一个全球唯一的MAC地址,并且一般来说无线AP在一段时间内不会移动;

2、设备在开启Wi-Fi的情况下,即可扫描并收集周围的AP信号,无论是否加密,是否已连接,甚至信号强度不足以显示在无线信号列表中,都可以获取到AP广播出来的MAC地址;

3、设备将这些能够标示AP的数据发送到位置服务器,服务器检索出每一个AP的地理位置,并结合每个信号的强弱程度,计算出设备的地理位置并返回到用户设备;

4、位置服务商要不断更新、补充自己的数据库,以保证数据的准确性。


               
代码:
                             
               
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public classWiFiInfoManager implements Serializable {
          privatestatic final long serialVersionUID= -4582739827003032383L;
          privateContext context;
          publicWiFiInfoManager(Context context) {
            super();
            this.context = context;
          }
          publicWifiInfo getWifiInfo() {
            WifiManager manager = (WifiManager)context
               .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info =new WifiInfo();
            info.mac =manager.getConnectionInfo().getBSSID();
            Log.i( TAG , WIFI MACis: + info.mac);
            returninfo;
          }
          publicclass WifiInfo {
            publicString mac;
            publicWifiInfo() {
              super();
            }
          }
        }

上面是取到WIFI的mac地址的方法,下面是把地址发送给google服务器,代码如下
                           
               

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public staticLocation getWIFILocation(WifiInfo wifi) {
            if(wifi == null) {
              Log.i( TAG , wifiisnull. );
              returnnull;
            }
            DefaultHttpClient client = newDefaultHttpClient();
            HttpPost post =new HttpPost( http://www.google.com/loc/json );
            JSONObject holder =new JSONObject();
            try{
              holder.put( version ,1.1.0);
              holder.put( host , maps.google.com );
              JSONObject data;
              JSONArray array =new JSONArray();
              if(wifi.mac != null wifi.mac.trim().length()  0) {
                data =new JSONObject();
               data.put( mac_address , wifi.mac);
               data.put( signal_strength ,8);
                data.put( age ,0);
                array.put(data);
              }
              holder.put( wifi_towers ,array);
              Log.i( TAG , request json: + holder.toString());
              StringEntity se = newStringEntity(holder.toString());
              post.setEntity(se);
              HttpResponse resp =client.execute(post);
              intstate =resp.getStatusLine().getStatusCode();
              if(state == HttpStatus.SC_OK) {
                HttpEntity entity =resp.getEntity();
                if(entity != null) {
                  BufferedReader br = newBufferedReader(
                      newInputStreamReader(entity.getContent()));
                  StringBuffer sb = newStringBuffer();
                  String resute = ;
                  while((resute =br.readLine()) != null) {
                    sb.append(resute);
                  }
                  br.close();
                  Log.i( TAG , response json: + sb.toString());
                  data = newJSONObject(sb.toString());
                  data = (JSONObject)data.get( location );
                  Location loc = newLocation(
                     android.location.LocationManager.NETWORK_PROVIDER);
                  loc.setLatitude((Double)data.get( latitude ));
                  loc.setLongitude((Double)data.get( longitude ));
                 loc.setAccuracy(Float.parseFloat(data.get( accuracy )
                      .toString()));
                  loc.setTime(System.currentTimeMillis());
                  returnloc;
                }else {
                  returnnull;
                }
              }else {
                Log.v( TAG , state + );
                returnnull;
              }
            }catch (Exception e) {
              Log.e( TAG ,e.getMessage());
              returnnull;
            }
          }

(3.1)而WIFI定位与基站定位的结合,笔者也在网上找到一个很好的文章,笔者对此就不做任何解释,直接给出网址:
                           
               http://www.jb51.net/article/52673.htm
                             

4. AGPS定位

AGPS(AssistedGPS:辅助全球卫星定位系统)是结合GSM或GPRS与传统卫星定位,利用基地台代送辅助卫星信息,以缩减GPS芯片获取卫星信号的延迟时间,受遮盖的室内也能借基地台讯号弥补,减轻GPS芯片对卫星的依赖度。和纯GPS、基地台三角定位比较,AGPS能提供范围更广、更省电、速度更快的定位服务,理想误差范围在10公尺以内,日本和美国都已经成熟运用AGPS于LBS服务(Location Based Service,基于位置的服务)。AGPS技术是一种结合了网络基站信息和GPS信息对移动台进行定位的技术,可以在GSM/GPRS、WCDMA和CDMA2000网络中使进行用。该技术需要在手机内增加GPS接收机模块,并改造手机的天线,同时要在移动网络上加建位置服务器、差分GPS基准站等设备。AGPS解决方案的优势主要体现在其定位精度上,在室外等空旷地区,其精度在正常的GPS工作环境下,可以达到10米左右,堪称目前定位精度最高的一种定位技术。该技术的另一优点为:首次捕获GPS信号的时间一般仅需几秒,不像GPS的首次捕获时间可能要2~3分钟



WiFi能够对用户进行定位。因为在Android、iOS和Windows Phone这些手机操作系统中内置了位置服务,由于每一个WiFi热点都有一个独一无二的Mac地址,智能手机开启WiFi后就会自动扫描附近热点并上传其位置信息,这样就建立了一个庞大的热点位置数据库。这个数据库是对用户进行定位的关键。

如果你的智能手机连接上了某个Wi-Fi热点,那么就可以调用数据库中附近所有热点的地理位置信息,而服务器会参考每个热点的信号强弱计算出设备的大致地理位置。

一、WiFi定位的原理

具体来说,WiFi能够定位,原理是这样的:

1、每一个无线AP(路由器)都有一个全球唯一的MAC地址,并且一般来说无线AP在一段时间内不会移动;

2、设备在开启Wi-Fi的情况下,即可扫描并收集周围的AP信号,无论是否加密,是否已连接,甚至信号强度不足以显示在无线信号列表中,都可以获取到AP广播出来的MAC地址;

3、设备将这些能够标示AP的数据发送到位置服务器,服务器检索出每一个AP的地理位置,并结合每个信号的强弱程度,计算出设备的地理位置并返回到用户设备;

4、位置服务商要不断更新、补充自己的数据库,以保证数据的准确性。

二、位置服务数据库的搭建

数据库中的数据主要来自于两个方面,一是用户提交的数据。Android手机用户在开启“使用无线网络定位”时会提示是否允许使用Google的定位服务,如果允许,用户的位置信息就被谷歌(微博)收集到。iPhone则会自动收集WiFi的MAC地址、GPS位置信息、运营商基站编码等,并发送给苹果公司的服务器。

同时谷歌、Skyhook两家位置服务提供商也在主动搜集WiFi等热点的位置信息。Google的街景拍摄车有一个重要的功能就是采集沿途的无线信号,并打上通过GPS定位出的坐标回传至服务器。Skyhook在美国及欧洲一些国家也是直接开着信号采集车采集AP和基站的信号数据。

三、如何防止被定位?

最直接的办法是关掉手机系统中的位置服务选项,以避免他人看到你的位置信息。

如果要杜绝位置服务商获取数据,难度就会比较高。用户需要不连接任何WiFi热点,并且不使用相关的位置服务。

也可以使用某些工具。例如谷歌曾发布一款选择退出工具,让无线路由器用户有效阻止谷歌搜集他们的数据。(瑞星)


关于定位原理网上很多,这里就不多说了。下面说怎么实现的,直接贴代码如下:

首先是Util类:

[java] view plaincopy
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3.   
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.HttpClient;  
  7. import org.apache.http.client.methods.HttpGet;  
  8. import org.apache.http.impl.client.DefaultHttpClient;  
  9. import org.json.JSONArray;  
  10. import org.json.JSONObject;  
  11.   
  12.   
  13. import android.content.Context;  
  14. import android.net.ConnectivityManager;  
  15. import android.net.NetworkInfo;  
  16. import android.util.Log;  
  17.   
  18. public class Util {  
  19.     //log的标签  
  20.     public static final String TAG = "location";  
  21.     public static final boolean DEBUG = true;  
  22.     public static final String LOCATION_URL = "http://www.google.com/loc/json";  
  23.     public static final String LOCATION_HOST = "maps.google.com";  
  24.       
  25.     public static void logi(String content){  
  26.         if(DEBUG) {  
  27.             Log.i(TAG, content);  
  28.         }  
  29.     }  
  30.       
  31.     public static void loge(String content){  
  32.         if(DEBUG) {  
  33.             Log.e(TAG, content);  
  34.         }  
  35.     }  
  36.       
  37.     public static void logd(String content){  
  38.         if(DEBUG) {  
  39.             Log.d(TAG, content);  
  40.         }  
  41.     }  
  42.       
  43.     /** 
  44.      * 获取地理位置 
  45.      *  
  46.      * @throws Exception 
  47.      */  
  48.     public static String getLocation(String latitude, String longitude) throws Exception {  
  49.         String resultString = "";  
  50.   
  51.         /** 这里采用get方法,直接将参数加到URL上 */  
  52.         String urlString = String.format("http://maps.google.cn/maps/geo?key=abcdefg&q=%s,%s", latitude, longitude);  
  53.         Util.logi("Util: getLocation: URL: " + urlString);  
  54.   
  55.         /** 新建HttpClient */  
  56.         HttpClient client = new DefaultHttpClient();  
  57.         /** 采用GET方法 */  
  58.         HttpGet get = new HttpGet(urlString);  
  59.         try {  
  60.             /** 发起GET请求并获得返回数据 */  
  61.             HttpResponse response = client.execute(get);  
  62.             HttpEntity entity = response.getEntity();  
  63.             BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent()));  
  64.             StringBuffer strBuff = new StringBuffer();  
  65.             String result = null;  
  66.             while ((result = buffReader.readLine()) != null) {  
  67.                 strBuff.append(result);  
  68.             }  
  69.             resultString = strBuff.toString();  
  70.   
  71.             /** 解析JSON数据,获得物理地址 */  
  72.             if (resultString != null && resultString.length() > 0) {  
  73.                 JSONObject jsonobject = new JSONObject(resultString);  
  74.                 JSONArray jsonArray = new JSONArray(jsonobject.get("Placemark").toString());  
  75.                 resultString = "";  
  76.                 for (int i = 0; i < jsonArray.length(); i++) {  
  77.                     resultString = jsonArray.getJSONObject(i).getString("address");  
  78.                 }  
  79.             }  
  80.         } catch (Exception e) {  
  81.             throw new Exception("获取物理位置出现错误:" + e.getMessage());  
  82.         } finally {  
  83.             get.abort();  
  84.             client = null;  
  85.         }  
  86.   
  87.         return resultString;  
  88.     }  
  89.       
  90.     /** 
  91.      * 判断网络是否可用 
  92.      * @param context 
  93.      * @return 
  94.      */  
  95.     public static boolean isNetworkAvaliable(Context context){  
  96.         ConnectivityManager manager = (ConnectivityManager) (context  
  97.                 .getSystemService(Context.CONNECTIVITY_SERVICE));  
  98.         NetworkInfo networkinfo = manager.getActiveNetworkInfo();  
  99.         return !(networkinfo == null || !networkinfo.isAvailable());  
  100.     }  
  101.       
  102.     /** 
  103.      * 判断网络类型 wifi  3G 
  104.      *  
  105.      * @param context 
  106.      * @return 
  107.      */  
  108.     public static  boolean isWifiNetwrokType(Context context) {  
  109.         ConnectivityManager connectivityManager = (ConnectivityManager) context  
  110.                 .getSystemService(Context.CONNECTIVITY_SERVICE);  
  111.         NetworkInfo info = connectivityManager.getActiveNetworkInfo();  
  112.   
  113.         if (info != null && info.isAvailable()) {  
  114.             if (info.getTypeName().equalsIgnoreCase("wifi")) {  
  115.                 return true;  
  116.             }   
  117.         }  
  118.         return false;  
  119.     }  
  120. }  

在MainActivity中根据当前网络环境,决定用WIFI定位还是基站定位

[java] view plaincopy
  1. import com.demo.location.cell.CellLocationManager;  
  2. import com.demo.location.wifi.WifiLocationManager;  
  3.   
  4. import android.app.Activity;  
  5. import android.content.BroadcastReceiver;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.os.Bundle;  
  9. import android.view.View;  
  10. import android.view.View.OnClickListener;  
  11. import android.widget.Button;  
  12. import android.widget.TextView;  
  13. import android.widget.Toast;  
  14.   
  15. public class MainActivity extends Activity {  
  16.       
  17.     private TextView mTextView;  
  18.     private Button mButton;  
  19.     private WifiLocationManager wifiLocation;  
  20.     private CellLocationManager cellLocation;  
  21.       
  22.     /** Called when the activity is first created. */  
  23.     @Override  
  24.     public void onCreate(Bundle savedInstanceState) {  
  25.         super.onCreate(savedInstanceState);  
  26.         setContentView(R.layout.main);  
  27.           
  28.         mTextView = (TextView) findViewById(R.id.tv_show_info);  
  29.         mButton = (Button) findViewById(R.id.btn_get_info);  
  30.         wifiLocation = new WifiLocationManager(MainActivity.this);  
  31.         cellLocation = new CellLocationManager(MainActivity.this);  
  32.           
  33.         mButton.setOnClickListener(new OnClickListener(){  
  34.   
  35.             @Override  
  36.             public void onClick(View v) {  
  37.                 // TODO Auto-generated method stub  
  38.                 Util.logi("MainActivity: on mButton Click!!!");  
  39.                 getLocation();  
  40.             }  
  41.               
  42.         });  
  43.     }  
  44.       
  45.     private void getLocation(){  
  46.         boolean isNet = Util.isNetworkAvaliable(MainActivity.this);  
  47.         if(!isNet){  
  48.             Toast.makeText(MainActivity.this"网络不可用:打开WIFI 或 数据连接!!!", Toast.LENGTH_LONG).show();  
  49.             Util.logd("MainActivity: getLocation: Net work is not avaliable, and return!!!");  
  50.             return;  
  51.         }  
  52.         boolean isWifi = Util.isWifiNetwrokType(MainActivity.this);  
  53.         if(isWifi){  
  54.             Util.logd("MainActivity: getLocation: Wifi定位");  
  55.             wifiLocation.getLocation(new WifiReceiver());  
  56.         }else{  
  57.             Util.logd("MainActivity: getLocation: 基站定位");  
  58.             String location = cellLocation.getLocationCell();  
  59.             mTextView.setText(location);  
  60.         }  
  61.     }  
  62.       
  63.       
  64.     class WifiReceiver extends BroadcastReceiver {  
  65.         public void onReceive(Context c, Intent intent) {  
  66.             Util.logi("get broadcastReceiver: SCAN_RESULTS_AVAILABLE_ACTION");  
  67.             String location = wifiLocation.getLocationWifi();  
  68.             mTextView.setText(location);  
  69.         }  
  70.     }  
  71. }  


1. WIFI定位:

WIFI定位的实现在WifiLocationManager.java里

[java] view plaincopy
  1. import java.io.BufferedReader;  
  2. import java.io.IOException;  
  3. import java.io.InputStreamReader;  
  4. import java.util.List;  
  5.   
  6. import org.apache.http.HttpEntity;  
  7. import org.apache.http.HttpResponse;  
  8. import org.apache.http.client.ClientProtocolException;  
  9. import org.apache.http.client.HttpClient;  
  10. import org.apache.http.client.methods.HttpPost;  
  11. import org.apache.http.entity.StringEntity;  
  12. import org.apache.http.impl.client.DefaultHttpClient;  
  13. import org.json.JSONArray;  
  14. import org.json.JSONObject;  
  15.   
  16. import com.demo.location.Util;  
  17.   
  18. import android.content.BroadcastReceiver;  
  19. import android.content.Context;  
  20. import android.content.IntentFilter;  
  21. import android.net.wifi.ScanResult;  
  22. import android.net.wifi.WifiManager;  
  23.   
  24. public class WifiLocationManager {  
  25.   
  26.     private Context mContext;  
  27.     private WifiManager wifiManager;  
  28.   
  29.     public WifiLocationManager(Context context){  
  30.         mContext = context;  
  31.         wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);  
  32.     }  
  33.       
  34.     public void getLocation(BroadcastReceiver receiver){  
  35.         mContext.registerReceiver(receiver, new IntentFilter(  
  36.                 WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));  
  37.         wifiManager.startScan();  
  38.     }  
  39.       
  40.     public List<ScanResult> getWifiList(){  
  41.         return wifiManager.getScanResults();  
  42.     }  
  43.       
  44.     public String getLocationWifi(){  
  45.   
  46.         /** 采用Android默认的HttpClient */  
  47.         HttpClient client = new DefaultHttpClient();  
  48.         /** 采用POST方法 */  
  49.         HttpPost post = new HttpPost(Util.LOCATION_URL);  
  50.         try {  
  51.             /** 构造POST的JSON数据 */  
  52.             JSONObject holder = new JSONObject();  
  53.             holder.put("version""1.1.0");  
  54.             holder.put("host", Util.LOCATION_HOST);  
  55.             holder.put("address_language""zh_CN");  
  56.             holder.put("request_address"true);  
  57.   
  58.             JSONArray towerarray = new JSONArray();  
  59.             List<ScanResult> wifiList = getWifiList();  
  60.             for (int i = 0; i < wifiList.size(); i++) {  
  61.                 JSONObject tower = new JSONObject();  
  62.                 tower.put("mac_address", wifiList.get(i).BSSID);  
  63.                 tower.put("ssid", wifiList.get(i).SSID);  
  64.                 tower.put("signal_strength", wifiList.get(i).level);  
  65.                 towerarray.put(tower);  
  66.             }  
  67.               
  68.             holder.put("wifi_towers", towerarray);  
  69.             Util.logd("holder.put: " + holder.toString());  
  70.               
  71.             StringEntity query = new StringEntity(holder.toString());  
  72.             post.setEntity(query);  
  73.   
  74.             /** 发出POST数据并获取返回数据 */  
  75.             HttpResponse response = client.execute(post);  
  76.             HttpEntity entity = response.getEntity();  
  77.             BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent()));  
  78.             StringBuffer strBuff = new StringBuffer();  
  79.             String result = null;  
  80.             while ((result = buffReader.readLine()) != null) {  
  81.                 strBuff.append(result);  
  82.             }  
  83.             Util.logd("result: " + strBuff.toString());  
  84.               
  85.             /** 解析返回的JSON数据获得经纬度 */  
  86.             JSONObject json = new JSONObject(strBuff.toString());  
  87.             JSONObject subjosn = new JSONObject(json.getString("location"));  
  88.   
  89.             String latitude = subjosn.getString("latitude");  
  90.             String longitude = subjosn.getString("longitude");  
  91.               
  92.             return Util.getLocation(latitude, longitude);  
  93.               
  94.         } catch(ClientProtocolException e){  
  95.             Util.loge("ClientProtocolException : " + e.getMessage());  
  96.         }catch(IOException e){  
  97.             Util.loge("IOException : " + e.getMessage());  
  98.         } catch (Exception e) {  
  99.             Util.loge("Exception : " + e.getMessage());  
  100.         } finally{  
  101.             post.abort();  
  102.             client = null;  
  103.         }  
  104.         return null;  
  105.     }  
  106. }  

2.基站定位

基站定位的实现在CellLocationManager.java中

[java] view plaincopy
  1. import java.io.BufferedReader;  
  2. import java.io.InputStreamReader;  
  3.   
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.HttpClient;  
  7. import org.apache.http.client.methods.HttpPost;  
  8. import org.apache.http.entity.StringEntity;  
  9. import org.apache.http.impl.client.DefaultHttpClient;  
  10. import org.json.JSONArray;  
  11. import org.json.JSONObject;  
  12.   
  13. import com.demo.location.Util;  
  14.   
  15. import android.content.Context;  
  16. import android.telephony.TelephonyManager;  
  17. import android.telephony.gsm.GsmCellLocation;  
  18.   
  19.   
  20. public class CellLocationManager {  
  21.   
  22.     private Context mContext;  
  23.     public CellLocationManager(Context context){  
  24.         mContext = context;  
  25.     }  
  26.       
  27.     /** 基站信息结构体 */  
  28.     public class SCell{  
  29.         public int MCC;  
  30.         public int MNC;  
  31.         public int LAC;  
  32.         public int CID;  
  33.     }  
  34.       
  35.     /** 
  36.      * 获取基站信息 
  37.      *  
  38.      * @throws Exception 
  39.      */  
  40.     private SCell getCellInfo() throws Exception {  
  41.         SCell cell = new SCell();  
  42.   
  43.         /** 调用API获取基站信息 */  
  44.         TelephonyManager mTelNet = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);  
  45.         GsmCellLocation location = (GsmCellLocation) mTelNet.getCellLocation();  
  46.         if (location == null)  
  47.             throw new Exception("获取基站信息失败");  
  48.   
  49.         String operator = mTelNet.getNetworkOperator();  
  50.         int mcc = Integer.parseInt(operator.substring(03));  
  51.         int mnc = Integer.parseInt(operator.substring(3));  
  52.         int cid = location.getCid();  
  53.         int lac = location.getLac();  
  54.   
  55.         /** 将获得的数据放到结构体中 */  
  56.         cell.MCC = mcc;  
  57.         cell.MNC = mnc;  
  58.         cell.LAC = lac;  
  59.         cell.CID = cid;  
  60.   
  61.         return cell;  
  62.     }  
  63.       
  64.     public String getLocationCell(){  
  65.   
  66.         SCell cell = null;  
  67.         try {  
  68.             cell = getCellInfo();  
  69.         } catch (Exception e1) {  
  70.             Util.loge("getLocationCell: getCellInfo: error: " + e1.getMessage());  
  71.             return null;  
  72.         }  
  73.         /** 采用Android默认的HttpClient */  
  74.         HttpClient client = new DefaultHttpClient();  
  75.         /** 采用POST方法 */  
  76.         HttpPost post = new HttpPost(Util.LOCATION_URL);  
  77.           
  78.         try {  
  79.             /** 构造POST的JSON数据 */  
  80.             JSONObject holder = new JSONObject();  
  81.             holder.put("version""1.1.0");  
  82.             holder.put("host", Util.LOCATION_HOST);  
  83.             holder.put("address_language""zh_CN");  
  84.             holder.put("request_address"true);  
  85.             holder.put("radio_type""gsm");  
  86.             holder.put("carrier""HTC");  
  87.   
  88.             JSONObject tower = new JSONObject();  
  89.             tower.put("mobile_country_code", cell.MCC);  
  90. //          Util.logi("getLocationCell: mobile_country_code = " + cell.MCC );  
  91.             tower.put("mobile_network_code", cell.MNC);  
  92. //          Util.logi("getLocationCell: mobile_network_code = " + cell.MNC );  
  93.             tower.put("cell_id", cell.CID);  
  94. //          Util.logi("getLocationCell: cell_id = " + cell.CID );  
  95.             tower.put("location_area_code", cell.LAC);  
  96. //          Util.logi("getLocationCell: location_area_code = " + cell.LAC );  
  97.   
  98.             JSONArray towerarray = new JSONArray();  
  99.             towerarray.put(tower);  
  100.             holder.put("cell_towers", towerarray);  
  101.   
  102.             StringEntity query = new StringEntity(holder.toString());  
  103.             Util.logi("getLocationCell: holder: " + holder.toString());  
  104.             post.setEntity(query);  
  105.   
  106.             /** 发出POST数据并获取返回数据 */  
  107.             HttpResponse response = client.execute(post);  
  108.             HttpEntity entity = response.getEntity();  
  109.             BufferedReader buffReader = new BufferedReader(new InputStreamReader(entity.getContent()));  
  110.             StringBuffer strBuff = new StringBuffer();  
  111.             String result = null;  
  112.             while ((result = buffReader.readLine()) != null) {  
  113.                 strBuff.append(result);  
  114.             }  
  115.   
  116.             /** 解析返回的JSON数据获得经纬度 */  
  117.             JSONObject json = new JSONObject(strBuff.toString());  
  118.             JSONObject subjosn = new JSONObject(json.getString("location"));  
  119.   
  120.             String latitude = subjosn.getString("latitude");  
  121.             String longitude = subjosn.getString("longitude");  
  122.               
  123.             return Util.getLocation(latitude, longitude);  
  124.               
  125.         } catch (Exception e) {  
  126.             Util.loge("getLocationCell: error: " + e.getMessage());  
  127.         } finally{  
  128.             post.abort();  
  129.             client = null;  
  130.         }  
  131.           
  132.         return null;  
  133.     }  
  134.       
  135.       
  136. }  


下载源代码请到:http://download.cs



0 0
原创粉丝点击