最近在看android关于定位的方式,查了很多资料,也做了相关实验,在手机上做了测试,下面总结:
一共有三种定位方式,一种是GPS,一种是通过网络的方式,一种则是在基于基站的方式,但是,不管哪种方式,都需要开启网络或者GPS
首先添加权限
- <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
- <uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/>
在COARSE_LOCATION是用于基站定位的时候用的,没有这个权限,在获取getCellLocation的时候报错。
第一种方式通过JASON来实现,是通过基站方式的,引用文章地址:http://www.cnblogs.com/dartagnan/archive/2011/3/9.html,下载只是实现定位的代码
- /**
- *Google定位的实现.<br/>
- *Geolocation的详细信息请参见:<br/>
- *<a
- *href="http://code.google.com/apis/gears/geolocation_network_protocol.html"mce_href="http://code.google.com/apis/gears/geolocation_network_protocol.html">
- *http://code.google.com/apis/gears/geolocation_network_protocol.html</a>
- */
- publicclassLocationActextendsActivity{
- privateTextViewtxtInfo;
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- Buttonbtn=(Button)findViewById(R.id.btnStart);
- txtInfo=(TextView)findViewById(R.id.txtInfo);
- btn.setOnClickListener(newButton.OnClickListener(){
- publicvoidonClick(Viewview){
- getLocation();
- }
- });
- }
- privatevoidgetLocation(){
- TelephonyManagertm=(TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
- GsmCellLocationgsmCell=(GsmCellLocation)tm.getCellLocation();
- intcid=gsmCell.getCid();
- intlac=gsmCell.getLac();
- StringnetOperator=tm.getNetworkOperator();
- intmcc=Integer.valueOf(netOperator.substring(0,3));
- intmnc=Integer.valueOf(netOperator.substring(3,5));
- JSONObjectholder=newJSONObject();
- JSONArrayarray=newJSONArray();
- JSONObjectdata=newJSONObject();
- 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(JSONExceptione){
- e.printStackTrace();
- }
- DefaultHttpClientclient=newDefaultHttpClient();
- HttpPosthttpPost=newHttpPost("http://www.google.com/loc/json");
- StringEntitystringEntity=null;
- try{
- stringEntity=newStringEntity(holder.toString());
- }catch(UnsupportedEncodingExceptione){
- e.printStackTrace();
- }
- httpPost.setEntity(stringEntity);
- HttpResponsehttpResponse=null;
- try{
- httpResponse=client.execute(httpPost);
- }catch(ClientProtocolExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- e.printStackTrace();
- }
- HttpEntityhttpEntity=httpResponse.getEntity();
- InputStreamis=null;
- try{
- is=httpEntity.getContent();
- }catch(IllegalStateExceptione){
- e.printStackTrace();
- }catch(IOExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- InputStreamReaderisr=newInputStreamReader(is);
- BufferedReaderreader=newBufferedReader(isr);
- StringBufferstringBuffer=newStringBuffer();
- try{
- Stringresult="";
- while((result=reader.readLine())!=null){
- stringBuffer.append(result);
- }
- }catch(IOExceptione){
- e.printStackTrace();
- }
- txtInfo.setText(stringBuffer.toString());
- }
- }
第二种通过严格的GPS来定位,引用文章地址: http://www.cnblogs.com/wisekingokok/archive/2011/09/06/2168479.html ,这里只引用代码
- publicclassMainActivityextendsActivity{
- privateLocationManagerlocationManager;
- privateGpsStatusgpsstatus;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //获取到LocationManager对象
- locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
- //根据设置的Criteria对象,获取最符合此标准的provider对象
- StringcurrentProvider=locationManager.getProvider(LocationManager.GPS_PROVIDER).getName();
- //根据当前provider对象获取最后一次位置信息
- LocationcurrentLocation=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(InterruptedExceptione){
- Log.e("Location",e.getMessage());
- }
- }
- }
- privateGpsStatus.ListenergpsListener=newGpsStatus.Listener(){
- //GPS状态发生变化时触发
- @Override
- publicvoidonGpsStatusChanged(intevent){
- //获取当前状态
- gpsstatus=locationManager.getGpsStatus(null);
- switch(event){
- //第一次定位时的事件
- caseGpsStatus.GPS_EVENT_FIRST_FIX:
- break;
- //开始定位的事件
- caseGpsStatus.GPS_EVENT_STARTED:
- break;
- //发送GPS卫星状态事件
- caseGpsStatus.GPS_EVENT_SATELLITE_STATUS:
- Toast.makeText(MainActivity.this,"GPS_EVENT_SATELLITE_STATUS",Toast.LENGTH_SHORT).show();
- Iterable<GpsSatellite>allSatellites=gpsstatus.getSatellites();
- Iterator<GpsSatellite>it=allSatellites.iterator();
- intcount=0;
- while(it.hasNext())
- {
- count++;
- }
- Toast.makeText(MainActivity.this,"SatelliteCount:"+count,Toast.LENGTH_SHORT).show();
- break;
- //停止定位事件
- caseGpsStatus.GPS_EVENT_STOPPED:
- Log.d("Location","GPS_EVENT_STOPPED");
- break;
- }
- }
- };
- //创建位置监听器
- privateLocationListenerlocationListener=newLocationListener(){
- //位置发生改变时调用
- @Override
- publicvoidonLocationChanged(Locationlocation){
- Log.d("Location","onLocationChanged");
- }
- //provider失效时调用
- @Override
- publicvoidonProviderDisabled(Stringprovider){
- Log.d("Location","onProviderDisabled");
- }
- //provider启用时调用
- @Override
- publicvoidonProviderEnabled(Stringprovider){
- Log.d("Location","onProviderEnabled");
- }
- //状态改变时调用
- @Override
- publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){
- Log.d("Location","onStatusChanged");
- }
- };
- }
第三种主要是通过网络的方式来定位,引用文章地址: http://www.cnblogs.com/wisekingokok/archive/2011/09/05/2167755.html ,这里只写代码
- packagecom.test;
- importjava.io.IOException;
- importjava.util.List;
- importandroid.app.Activity;
- importandroid.location.Address;
- importandroid.location.Criteria;
- importandroid.location.Geocoder;
- importandroid.location.Location;
- importandroid.location.LocationListener;
- importandroid.location.LocationManager;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.widget.Toast;
- publicclassMainActivityextendsActivity{
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- //获取到LocationManager对象
- LocationManagerlocationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
- //创建一个Criteria对象
- Criteriacriteria=newCriteria();
- //设置粗略精确度
- criteria.setAccuracy(Criteria.ACCURACY_COARSE);
- //设置是否需要返回海拔信息
- criteria.setAltitudeRequired(false);
- //设置是否需要返回方位信息
- criteria.setBearingRequired(false);
- //设置是否允许付费服务
- criteria.setCostAllowed(true);
- //设置电量消耗等级
- criteria.setPowerRequirement(Criteria.POWER_HIGH);
- //设置是否需要返回速度信息
- criteria.setSpeedRequired(false);
- //根据设置的Criteria对象,获取最符合此标准的provider对象
- StringcurrentProvider=locationManager.getBestProvider(criteria,true);
- Log.d("Location","currentProvider:"+currentProvider);
- //根据当前provider对象获取最后一次位置信息
- LocationcurrentLocation=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(InterruptedExceptione){
- Log.e("Location",e.getMessage());
- }
- }
- //解析地址并显示
- GeocodergeoCoder=newGeocoder(this);
- try{
- intlatitude=(int)currentLocation.getLatitude();
- intlongitude=(int)currentLocation.getLongitude();
- List<Address>list=geoCoder.getFromLocation(latitude,longitude,2);
- for(inti=0;i<list.size();i++){
- Addressaddress=list.get(i);
- Toast.makeText(MainActivity.this,address.getCountryName()+address.getAdminArea()+address.getFeatureName(),Toast.LENGTH_LONG).show();
- }
- }catch(IOExceptione){
- Toast.makeText(MainActivity.this,e.getMessage(),Toast.LENGTH_LONG).show();
- }
- }
- //创建位置监听器
- privateLocationListenerlocationListener=newLocationListener(){
- //位置发生改变时调用
- @Override
- publicvoidonLocationChanged(Locationlocation){
- Log.d("Location","onLocationChanged");
- Log.d("Location","onLocationChangedLatitude"+location.getLatitude());
- Log.d("Location","onLocationChangedlocation"+location.getLongitude());
- }
- //provider失效时调用
- @Override
- publicvoidonProviderDisabled(Stringprovider){
- Log.d("Location","onProviderDisabled");
- }
- //provider启用时调用
- @Override
- publicvoidonProviderEnabled(Stringprovider){
- Log.d("Location","onProviderEnabled");
- }
- //状态改变时调用
- @Override
- publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras){
- Log.d("Location","onStatusChanged");
- }
- };
- }
Android定位技术详解
本文详细介绍Android平台上的三种定位技术:GPS定位、基站定位和网络定位。通过具体代码示例展示了如何实现这些定位功能,并解释了相关权限配置。
1573

被折叠的 条评论
为什么被折叠?



