当前位置:首页 > 芯闻号 > 充电吧
[导读]最近在看android关于定位的方式,查了很多资料,也做了相关实验,在手机上做了测试,下面总结:一共有三种定位方式,一种是GPS,一种是通过网络的方式,一种则是在基于基站的方式,但是,不管哪种方式,都

最近在看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");
         }
     };
 }



本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
换一批
延伸阅读

罗德与施瓦茨与SmartViser携手开发了一种用于测试符合欧盟销售的智能手机和平板电脑的新Energy Efficiency Index(EEI)标签法规的解决方案。该解决方案的核心是R&S CMX500,这是...

关键字: 智能手机 Android iOS

加工工艺的优劣直接影响着产品的加工质量及生产成本,往往小小的优化可以对产品的生产效率带来极大的提升。鉴于此,针对斜口法兰的结构特点及技术要求,制定了合理的加工工艺。钻削是一种应用极其广泛的加工方式,但在斜面、锥面上钻孔会...

关键字: 钻削 夹具 定位

(全球TMT2023年8月24日讯)2023年8月23日,时值实时3D引擎Unity在华设立合资公司Unity中国一周年之际,Unity中国正式推出Unity中国版引擎——团结引擎。Unity全球CEO John Ri...

关键字: UNITY CE Android 开发者

报告显示:全球电商 App 获客花费接近50亿美元 北京2023年8月23日 /美通社/ -- 全球营销衡量与体验管理平台 AppsFlyer 近日发布《2023 电商 App 营销现状报告》。尽管面临全球经...

关键字: APPS BSP iOS Android

针对商业领域的假冒问题,利用RFID射频识别技术可扩充、灵活、安全等特点,结合一次一密认证机制,研究读写器与电子标签的初始化和电子标签的验证,研发设计出来的一种新型安全的防伪技术。

关键字: RFID技术 定位 防伪

数字机顶盒是一种数字技术下的多媒体娱乐中心,可以实现电视节目接收、播放、存储、网络应用等多种功能。随着科技的发展,数字机顶盒的设计方案也在不断进步和优化。本文将介绍数字机顶盒设计的几种实现方案。

关键字: 数字机顶盒 Android Linux

GPS定位技术的出现与发展,为工程测量技术带来了革命性的变化,从根本上改变了工程测量的工作方式。

关键字: GPS系统 定位 工程测量

在当今科技发展迅猛的时代,无人驾驶车辆已经成为人们关注的热点话题。作为无人驾驶技术中关键的感知设备之一,激光雷达技术起着至关重要的作用。本文将详细探讨激光雷达技术在无人驾驶中的作用,并分析其优势和未来发展趋势。

关键字: 无人驾驶 激光雷达 定位

21ic 近日获悉,原小米 9 号创始员工李明在社交媒体平台公布了旗下首款产品乐天派桌面机器人,为全球首款 Android 桌面机器人,面向极客和发烧友的 AI + 机器人。据悉,李明两个月前宣布创业并进军 AI 领域,...

关键字: 小米 Android 桌面机器人 AI

尽管安装增长放缓,全球游戏 App 获客花费仍高达 267 亿美元 经济低迷导致 2023 游戏 App 营销优先考虑收入指标,用户增长次之 北京2023年3月9日 /美通社/ -- 今天,全球营销衡量与体验管理平台...

关键字: APPS iOS Android BSP
关闭
关闭