android 三种定位方式
扫描二维码
随时随地手机看文章
最近在看android关于定位的方式,查了很多资料,也做了相关实验,在手机上做了测试,下面总结:
一共有三种定位方式,一种是GPS,一种是通过网络的方式,一种则是在基于基站的方式,但是,不管哪种方式,都需要开启网络或者GPS
首先添加权限
在COARSE_LOCATION是用于基站定位的时候用的,没有这个权限,在获取getCellLocation的时候报错。
第一种方式通过JASON来实现,是通过基站方式的,实现定位的代码
/**
* Google定位的实现.
* Geolocation的详细信息请参见:
*
* http://code.google.com/apis/gears/geolocation_network_protocol.html
*/
public class LocationAct extends Activity {
private TextView txtInfo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btnStart);
txtInfo = (TextView) findViewById(R.id.txtInfo);
btn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
getLocation();
}
});
}
private void getLocation() {
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation gsmCell = (GsmCellLocation) tm.getCellLocation();
int cid = gsmCell.getCid();
int lac = gsmCell.getLac();
String netOperator = tm.getNetworkOperator();
int mcc = Integer.valueOf(netOperator.substring(0, 3));
int mnc = Integer.valueOf(netOperator.substring(3, 5));
JSONObject holder = new JSONObject();
JSONArray array = new JSONArray();
JSONObject data = new JSONObject();
try {
holder.put("version", "1.1.0");
holder.put("host", "maps.google.com");
holder.put("address_language", "zh_CN");
holder.put("request_address", true);
holder.put("radio_type", "gsm");
holder.put("carrier", "HTC");
data.put("cell_id", cid);
data.put("location_area_code", lac);
data.put("mobile_countyr_code", mcc);
data.put("mobile_network_code", mnc);
array.put(data);
holder.put("cell_towers", array);
} catch (JSONException e) {
e.printStackTrace();
}
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://www.google.com/loc/json");
StringEntity stringEntity = null;
try {
stringEntity = new StringEntity(holder.toString());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = null;
try {
httpResponse = client.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = null;
try {
is = httpEntity.getContent();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader reader = new BufferedReader(isr);
StringBuffer stringBuffer = new StringBuffer();
try {
String result = "";
while ((result = reader.readLine()) != null) {
stringBuffer.append(result);
}
} catch (IOException e) {
e.printStackTrace();
}
txtInfo.setText(stringBuffer.toString());
}
}
第二种通过严格的GPS来定位,这里引用代码
public class MainActivity extends Activity { private LocationManager locationManager; private GpsStatus gpsstatus; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获取到LocationManager对象 locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); //根据设置的Criteria对象,获取最符合此标准的provider对象 String currentProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER).getName(); //根据当前provider对象获取最后一次位置信息 Location currentLocation = locationManager.getLastKnownLocation(currentProvider); //如果位置信息为null,则请求更新位置信息 if(currentLocation == null){ locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener); } //增加GPS状态监听器 locationManager.addGpsStatusListener(gpsListener); //直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度 //每隔10秒获取一次位置信息 while(true){ currentLocation = locationManager.getLastKnownLocation(currentProvider); if(currentLocation != null){ Log.d("Location", "Latitude: " + currentLocation.getLatitude()); Log.d("Location", "location: " + currentLocation.getLongitude()); break; }else{ Log.d("Location", "Latitude: " + 0); Log.d("Location", "location: " + 0); } try { Thread.sleep(10000); } catch (InterruptedException e) { Log.e("Location", e.getMessage()); } } } private GpsStatus.Listener gpsListener = new GpsStatus.Listener(){ //GPS状态发生变化时触发 @Override public void onGpsStatusChanged(int event) { //获取当前状态 gpsstatus=locationManager.getGpsStatus(null); switch(event){ //第一次定位时的事件 case GpsStatus.GPS_EVENT_FIRST_FIX: break; //开始定位的事件 case GpsStatus.GPS_EVENT_STARTED: break; //发送GPS卫星状态事件 case GpsStatus.GPS_EVENT_SATELLITE_STATUS: Toast.makeText(MainActivity.this, "GPS_EVENT_SATELLITE_STATUS", Toast.LENGTH_SHORT).show(); IterableallSatellites = gpsstatus.getSatellites(); Iteratorit=allSatellites.iterator(); int count = 0; while(it.hasNext()) { count++; } Toast.makeText(MainActivity.this, "Satellite Count:" + count, Toast.LENGTH_SHORT).show(); break; //停止定位事件 case GpsStatus.GPS_EVENT_STOPPED: Log.d("Location", "GPS_EVENT_STOPPED"); break; } } }; //创建位置监听器 private LocationListener locationListener = new LocationListener(){ //位置发生改变时调用 @Override public void onLocationChanged(Location location) { Log.d("Location", "onLocationChanged"); } //provider失效时调用 @Override public void onProviderDisabled(String provider) { Log.d("Location", "onProviderDisabled"); } //provider启用时调用 @Override public void onProviderEnabled(String provider) { Log.d("Location", "onProviderEnabled"); } //状态改变时调用 @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Location", "onStatusChanged"); } }; }
第三种主要是通过网络的方式来定位,代码
package com.test; import java.io.IOException; import java.util.List; import android.app.Activity; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import android.widget.Toast; public class MainActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //获取到LocationManager对象 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); //创建一个Criteria对象 Criteria criteria = new Criteria(); //设置粗略精确度 criteria.setAccuracy(Criteria.ACCURACY_COARSE); //设置是否需要返回海拔信息 criteria.setAltitudeRequired(false); //设置是否需要返回方位信息 criteria.setBearingRequired(false); //设置是否允许付费服务 criteria.setCostAllowed(true); //设置电量消耗等级 criteria.setPowerRequirement(Criteria.POWER_HIGH); //设置是否需要返回速度信息 criteria.setSpeedRequired(false); //根据设置的Criteria对象,获取最符合此标准的provider对象 String currentProvider = locationManager.getBestProvider(criteria, true); Log.d("Location", "currentProvider: " + currentProvider); //根据当前provider对象获取最后一次位置信息 Location currentLocation = locationManager.getLastKnownLocation(currentProvider); //如果位置信息为null,则请求更新位置信息 if(currentLocation == null){ locationManager.requestLocationUpdates(currentProvider, 0, 0, locationListener); } //直到获得最后一次位置信息为止,如果未获得最后一次位置信息,则显示默认经纬度 //每隔10秒获取一次位置信息 while(true){ currentLocation = locationManager.getLastKnownLocation(currentProvider); if(currentLocation != null){ Log.d("Location", "Latitude: " + currentLocation.getLatitude()); Log.d("Location", "location: " + currentLocation.getLongitude()); break; }else{ Log.d("Location", "Latitude: " + 0); Log.d("Location", "location: " + 0); } try { Thread.sleep(10000); } catch (InterruptedException e) { Log.e("Location", e.getMessage()); } } //解析地址并显示 Geocoder geoCoder = new Geocoder(this); try { int latitude = (int) currentLocation.getLatitude(); int longitude = (int) currentLocation.getLongitude(); Listlist = geoCoder.getFromLocation(latitude, longitude, 2); for(int i=0; i<list.size(); i++){ Address address = list.get(i); Toast.makeText(MainActivity.this, address.getCountryName() + address.getAdminArea() + address.getFeatureName(), Toast.LENGTH_LONG).show(); } } catch (IOException e) { Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show(); } } //创建位置监听器 private LocationListener locationListener = new LocationListener(){ //位置发生改变时调用 @Override public void onLocationChanged(Location location) { Log.d("Location", "onLocationChanged"); Log.d("Location", "onLocationChanged Latitude" + location.getLatitude()); Log.d("Location", "onLocationChanged location" + location.getLongitude()); } //provider失效时调用 @Override public void onProviderDisabled(String provider) { Log.d("Location", "onProviderDisabled"); } //provider启用时调用 @Override public void onProviderEnabled(String provider) { Log.d("Location", "onProviderEnabled"); } //状态改变时调用 @Override public void onStatusChanged(String provider, int status, Bundle extras) { Log.d("Location", "onStatusChanged"); } }; }