android 4种定位原理及实现——2

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

首先是Util类:

  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定位还是基站定位

  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里

  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中

  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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值