前文中所提到的Cell-ID和WI-FI定位方法,在Android官方文档《Obtaining User Location》中并入Network Location Provider一类,与GPS地位等同。前文中介绍的方法虽然可行,但是需要开发者处理比较多的数据。实际上,不必这么麻烦,还有更简单的方法,android.location中的LocationManager封装了地理位置信息的接口,提供了GPS_PROVIDER和NETWORK_PROVIDER等。
如果开发的应用需要高精确性,那么可使用GPS_PROVIDER,但这也意味着应用无法在室内使用,待机时间缩短,响应时间稍长等问题;如果开发的应用需要快速反应,对精度要求不怎么高,并且要尽可能节省电量,那么使用NETWORK_PROVIDER是不错的选择。这里提一下,还有一个PASSIVE_PROVIDER,在实际应用中较少使用。
提到GPS(Global Positioning System),那就顺便说说题外话,由于GPS前身来自于美国军方,后来“军转民”。尽管不收费,但是出于各自国家战略安全和商业利益考量,欧盟发起了伽利略定位系统(Gallileo Postionting System),俄罗斯建立了格洛纳斯(GLONASS),中国也开发了北斗卫星导航系统。尽管呈现出竞争格局,但是目前在非军用移动设备上,–例如手机、MID等,GPS占据了巨大的市场份额。目前来看,Android对GPS的支持还是相当给力,不过也希望未来能够在Android上收到来自北斗的信号。
言归正传,如下代码就是设置从Network中获取位置:
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocLis);
上面的代码需要对应的权限:android.permission.ACCESS_COARSE_LOCATION,同样,如果是GPS_PROVIDER,则需要权限android.permission.ACCESS_FINE_LOCATION。如果代码里使用了两个PROVIDER,则只需要一个权限即可:android.permission.ACCESS_FINE_LOCATION。
以下是整个过程的代码,由于目的只是技术验证,因此未做效率、健壮性等考虑,不过这并不妨碍我们对比四种获取locaiton方式的差异,其中的优劣由读者自行评判:
public class DemoActivity extends Activity {
private static final String TAG = "DemoActivity";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void onRequestLocation(View view) {
switch (view.getId()){
case R.id.gpsBtn:
Log.d(TAG, "GPS button is clicked");
requestGPSLocation();
break;
case R.id.telBtn:
Log.d(TAG, "CellID button is clicked");
requestTelLocation();
break;
case R.id.wifiBtn:
Log.d(TAG, "WI-FI button is clicked");
requestWIFILocation();
break;
case R.id.netBtn:
Log.d(TAG, "Network button is clicked");
requestNetworkLocation();
break;
}
}
private void requestTelLocation() {
TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// MCC+MNC. Unreliable on CDMA networks
String operator = mTelMan.getNetworkOperator();
String mcc = operator.substring(0, 3);
String mnc = operator.substring(3);
GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
int cid = location.getCid();
int lac = location.getLac();
JSONObject tower = new JSONObject();
try {
tower.put("cell_id", cid);
tower.put("location_area_code", lac);
tower.put("mobile_country_code", mcc);
tower.put("mobile_network_code", mnc);
} catch (JSONException e) {
Log.e(TAG, "call JSONObject's put failed", e);
}
JSONArray array = new JSONArray();
array.put(tower);
List list = mTelMan.getNeighboringCellInfo();
Iterator iter = list.iterator();
NeighboringCellInfo cellInfo;
JSONObject tempTower;
while (iter.hasNext()) {
cellInfo = iter.next();
tempTower = new JSONObject();
try {
tempTower.put("cell_id", cellInfo.getCid());
tempTower.put("location_area_code", cellInfo.getLac());
tempTower.put("mobile_country_code", mcc);
tempTower.put("mobile_network_code", mnc);
} catch (JSONException e) {
Log.e(TAG, "call JSONObject's put failed", e);
}
array.put(tempTower);
}
JSONObject object = createJSONObject("cell_towers", array);
requestLocation(object);
}
private void requestWIFILocation() {
WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiMan.getConnectionInfo();
String mac = info.getMacAddress();
String ssid = info.getSSID();
JSONObject wifi = new JSONObject();
try {
wifi.put("mac_address", mac);
wifi.put("ssid", ssid);
} catch (JSONException e) {
e.printStackTrace();
}
JSONArray array = new JSONArray();
array.put(wifi);
JSONObject object = createJSONObject("wifi_towers", array);
requestLocation(object);
}
private void requestLocation(JSONObject object) {
Log.d(TAG, "requestLocation: " + object.toString());
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
try {
StringEntity entity = new StringEntity(object.toString());
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuffer buffer = new StringBuffer();
String result = br.readLine();
while (result != null) {
buffer.append(result);
result = br.readLine();
}
Log.d(TAG, buffer.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private JSONObject createJSONObject(String arrayName, JSONArray array) {
JSONObject object = new JSONObject();
try {
object.put("version", "1.1.0");
object.put("host", "maps.google.com");
object.put(arrayName, array);
} catch (JSONException e) {
Log.e(TAG, "call JSONObject's put failed", e);
}
return object;
}
private void requestGPSLocation() {
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60, 100, mLocLis);
}
private void requestNetworkLocation() {
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60, 100, mLocLis);
}
private LocationListener mLocLis = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged, provider = " + provider);
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled, provider = " + provider);
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled, provider = " + provider);
}
@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.d(TAG, "latitude: " + latitude + ", longitude: " + longitude);
}
};
}