Android之GPS定位详解
一、LocationManager
LocationMangager,位置管理器。要想操作定位相关设备,必须先定义个LocationManager。我们可以通过如下代码创建LocationManger对象。
LocationManger locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
二、LocationListener
LocationListener,位置监听,监听位置变化,监听设备开关与状态。

    private LocationListener locationListener=new LocationListener() {
        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            updateView(location);
            Log.i(TAG, "时间:"+location.getTime()); 
            Log.i(TAG, "经度:"+location.getLongitude()); 
            Log.i(TAG, "纬度:"+location.getLatitude()); 
            Log.i(TAG, "海拔:"+location.getAltitude()); 
        }
        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
            //GPS状态为可见时
            case LocationProvider.AVAILABLE:
                Log.i(TAG, "当前GPS状态为可见状态");
                break;
            //GPS状态为服务区外时
            case LocationProvider.OUT_OF_SERVICE:
                Log.i(TAG, "当前GPS状态为服务区外状态");
                break;
            //GPS状态为暂停服务时
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Log.i(TAG, "当前GPS状态为暂停服务状态");
                break;
            }
        }
        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
            Location location=lm.getLastKnownLocation(provider);
            updateView(location);
        }
        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
            updateView(null);
        }
    };

三、Location
Location,位置信息,通过Location可以获取时间、经纬度、海拔等位置信息。上面采用locationListener里面的onLocationChanged()来获取location,下面讲述如何主动获取location。
Location location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
system.out.println("时间:"+location.getTime());
system.out.println("经度:"+location.getLongitude());
注意:Location location=new Location(LocationManager.GPS_PROVIDER)方式获取的location的各个参数值都是为0。
四、GpsStatus.Listener
GpsStatus.Listener ,GPS状态监听,包括GPS启动、停止、第一次定位、卫星变化等事件。

//状态监听
GpsStatus.Listener listener = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
switch (event) {
//第一次定位
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.i(TAG, "第一次定位");
break;
//卫星状态改变
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.i(TAG, "卫星状态改变");
//获取当前状态
GpsStatus gpsStatus=lm.getGpsStatus(null);
//获取卫星颗数的默认最大值
int maxSatellites = gpsStatus.getMaxSatellites();
//创建一个迭代器保存所有卫星
Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
int count = 0;
while (iters.hasNext() && count <= maxSatellites) {
GpsSatellite s = iters.next();
count++;
}
System.out.println("搜索到:"+count+"颗卫星");
break;
//定位启动
case GpsStatus.GPS_EVENT_STARTED:
Log.i(TAG, "定位启动");
break;
//定位结束
case GpsStatus.GPS_EVENT_STOPPED:
Log.i(TAG, "定位结束");
break;
}
};
};
//绑定监听状态
lm.addGpsStatusListener(listener);

五、GpsStatus

GpsStatus,GPS状态信息,上面在卫星状态变化时,我们就用到了GpsStatus。 //实例化
GpsStatus gpsStatus = locationManager.getGpsStatus(null); // 获取当前状态
//获取默认最大卫星数
int maxSatellites = gpsStatus.getMaxSatellites();
//获取第一次定位时间(启动到第一次定位)
int costTime=gpsStatus.getTimeToFirstFix();
//获取卫星
Iterable<GpsSatellite> iterable=gpsStatus.getSatellites();
//一般再次转换成Iterator
Iterator<GpsSatellite> itrator=iterable.iterator();

六、GpsSatellite
    
GpsSatellite,定位卫星,包含卫星的方位、高度、伪随机噪声码、信噪比等信息。

//获取卫星
Iterable<GpsSatellite> iterable=gpsStatus.getSatellites();
//再次转换成Iterator
Iterator<GpsSatellite> itrator=iterable.iterator();
//通过遍历重新整理为ArrayList
ArrayList<GpsSatellite> satelliteList=new ArrayList<GpsSatellite>();
int count=0;
int maxSatellites=gpsStatus.getMaxSatellites();
while (itrator.hasNext() && count <= maxSatellites) {
GpsSatellite satellite = itrator.next();
satelliteList.add(satellite);
count++;
}
System.out.println("总共搜索到"+count+"颗卫星");
//输出卫星信息
for(int i=0;i<satelliteList.size();i++){
//卫星的方位角,浮点型数据
System.out.println(satelliteList.get(i).getAzimuth());
//卫星的高度,浮点型数据
System.out.println(satelliteList.get(i).getElevation());
//卫星的伪随机噪声码,整形数据
System.out.println(satelliteList.get(i).getPrn());
//卫星的信噪比,浮点型数据
System.out.println(satelliteList.get(i).getSnr());
//卫星是否有年历表,布尔型数据
System.out.println(satelliteList.get(i).hasAlmanac());
//卫星是否有星历表,布尔型数据
System.out.println(satelliteList.get(i).hasEphemeris());
//卫星是否被用于近期的GPS修正计算
System.out.println(satelliteList.get(i).hasAlmanac());
}

为了便于理解,接下来模拟一个案例,如何在程序代码中使用GPS获取位置信息。
第一步:新建一个Android工程项目,命名为mygps,目录结构如下

第二步:修改main.xml布局文件,修改内容如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:editable="false"
android:id="@+id/editText"/>
</LinearLayout>

第三步:实用Adnroid平台的GPS设备,需要添加上权限
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
第四步:修改核心组件activity,修改内容如下

package com.ljq.activity; import java.util.Iterator; import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast; public class GpsActivity extends Activity {
private EditText editText;
private LocationManager lm;
private static final String TAG="GpsActivity";
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
lm.removeUpdates(locationListener);
}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editText=(EditText)findViewById(R.id.editText);
        lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        //判断GPS是否正常启动
        if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();
            //返回开启GPS导航设置界面
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
            startActivityForResult(intent,0); 
            return;
        }
        //为获取地理位置信息时设置查询条件
        String bestProvider = lm.getBestProvider(getCriteria(), true);
        //获取位置信息
        //如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDER
        Location location= lm.getLastKnownLocation(bestProvider);    
        updateView(location);
        //监听状态
        lm.addGpsStatusListener(listener);
        //绑定监听,有4个参数    
        //参数1,设备:有GPS_PROVIDER和NETWORK_PROVIDER两种
        //参数2,位置信息更新周期,单位毫秒    
        //参数3,位置变化最小距离:当位置距离变化超过此值时,将更新位置信息    
        //参数4,监听    
        //备注:参数2和3,如果参数3不为0,则以参数3为准;参数3为0,则通过时间来定时更新;两者为0,则随时刷新   
        // 1秒更新一次,或最小位移变化超过1米更新一次;
        //注意:此处更新准确度非常低,推荐在service里面启动一个Thread,在run中sleep(10000);然后执行handler.sendMessage(),更新位置
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
    }
    //位置监听
    private LocationListener locationListener=new LocationListener() {
        /**
         * 位置信息变化时触发
         */
        public void onLocationChanged(Location location) {
            updateView(location);
            Log.i(TAG, "时间:"+location.getTime()); 
            Log.i(TAG, "经度:"+location.getLongitude()); 
            Log.i(TAG, "纬度:"+location.getLatitude()); 
            Log.i(TAG, "海拔:"+location.getAltitude()); 
        }
        /**
         * GPS状态变化时触发
         */
        public void onStatusChanged(String provider, int status, Bundle extras) {
            switch (status) {
            //GPS状态为可见时
            case LocationProvider.AVAILABLE:
                Log.i(TAG, "当前GPS状态为可见状态");
                break;
            //GPS状态为服务区外时
            case LocationProvider.OUT_OF_SERVICE:
                Log.i(TAG, "当前GPS状态为服务区外状态");
                break;
            //GPS状态为暂停服务时
            case LocationProvider.TEMPORARILY_UNAVAILABLE:
                Log.i(TAG, "当前GPS状态为暂停服务状态");
                break;
            }
        }
        /**
         * GPS开启时触发
         */
        public void onProviderEnabled(String provider) {
            Location location=lm.getLastKnownLocation(provider);
            updateView(location);
        }
        /**
         * GPS禁用时触发
         */
        public void onProviderDisabled(String provider) {
            updateView(null);
        }
    };
    //状态监听
    GpsStatus.Listener listener = new GpsStatus.Listener() {
        public void onGpsStatusChanged(int event) {
            switch (event) {
            //第一次定位
            case GpsStatus.GPS_EVENT_FIRST_FIX:
                Log.i(TAG, "第一次定位");
                break;
            //卫星状态改变
            case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                Log.i(TAG, "卫星状态改变");
                //获取当前状态
                GpsStatus gpsStatus=lm.getGpsStatus(null);
                //获取卫星颗数的默认最大值
                int maxSatellites = gpsStatus.getMaxSatellites();
                //创建一个迭代器保存所有卫星 
                Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();
                int count = 0;     
                while (iters.hasNext() && count <= maxSatellites) {     
                    GpsSatellite s = iters.next();     
                    count++;     
                }   
                System.out.println("搜索到:"+count+"颗卫星");
                break;
            //定位启动
            case GpsStatus.GPS_EVENT_STARTED:
                Log.i(TAG, "定位启动");
                break;
            //定位结束
            case GpsStatus.GPS_EVENT_STOPPED:
                Log.i(TAG, "定位结束");
                break;
            }
        };
    };
    /**
     * 实时更新文本内容
     * 
     * @param location
     */
    private void updateView(Location location){
        if(location!=null){
            editText.setText("设备位置信息\n\n经度:");
            editText.append(String.valueOf(location.getLongitude()));
            editText.append("\n纬度:");
            editText.append(String.valueOf(location.getLatitude()));
        }else{
            //清空EditText对象
            editText.getEditableText().clear();
        }
    }
    /**
     * 返回查询条件
     * @return
     */
    private Criteria getCriteria(){
        Criteria criteria=new Criteria();
        //设置定位精确度 Criteria.ACCURACY_COARSE比较粗略,Criteria.ACCURACY_FINE则比较精细 
        criteria.setAccuracy(Criteria.ACCURACY_FINE);    
        //设置是否要求速度
        criteria.setSpeedRequired(false);
        // 设置是否允许运营商收费  
        criteria.setCostAllowed(false);
        //设置是否需要方位信息
        criteria.setBearingRequired(false);
        //设置是否需要海拔信息
        criteria.setAltitudeRequired(false);
        // 设置对电源的需求  
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        return criteria;
    }
}

第五步:启动模拟器,如果启动完成,请在Myeclipse中按如下选项一步一步操作:Emulator Control->Location Controls->Manual->选中Decimal->输入经纬度,类似如下

演示效果如下:

Android之GPS定位详解的更多相关文章
- Android入门之GPS定位详解
		一.LocationManager LocationMangager,位置管理器.要想操作定位相关设备,必须先定义个LocationManager. LocationManger locationMa ... 
- 给 Android 开发者的 RxJava 详解
		我从去年开始使用 RxJava ,到现在一年多了.今年加入了 Flipboard 后,看到 Flipboard 的 Android 项目也在使用 RxJava ,并且使用的场景越来越多 .而最近这几个 ... 
- Android中Intent组件详解
		Intent是不同组件之间相互通讯的纽带,封装了不同组件之间通讯的条件.Intent本身是定义为一个类别(Class),一个Intent对象表达一个目的(Goal)或期望(Expectation),叙 ... 
- Android开发之MdiaPlayer详解
		Android开发之MdiaPlayer详解 MediaPlayer类可用于控制音频/视频文件或流的播放,我曾在<Android开发之基于Service的音乐播放器>一文中介绍过它的使用. ... 
- 转:给 Android 开发者的 RxJava 详解
		转自: http://gank.io/post/560e15be2dca930e00da1083 评注:多图解析,但是我还是未看懂. 前言 我从去年开始使用 RxJava ,到现在一年多了.今年加入 ... 
- 《Android NFC 开发实战详解 》简介+源码+样章+勘误ING
		<Android NFC 开发实战详解>简介+源码+样章+勘误ING SkySeraph Mar. 14th 2014 Email:skyseraph00@163.com 更多精彩请直接 ... 
- Android开发之InstanceState详解
		Android开发之InstanceState详解 本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ... 
- ANDROID L——Material Design详解(UI控件)
		转载请注明本文出自大苞米的博客(http://blog.csdn.net/a396901990),谢谢支持! Android L: Google已经确认Android L就是Android Lolli ... 
- android bundle存放数据详解
		转载自:android bundle存放数据详解 正如大家所知道,Activity之间传递数据,是将数据存放在Intent或者Bundle中 例如: 将数据存放倒Intent中传递: 将数据放到Bun ... 
随机推荐
- C#多线程编程实战(一):线程基础
			1.1 简介 为了防止一个应用程序控制CPU而导致其他应用程序和操作系统本身永远被挂起这一可能情况,操作系统不得不使用某种方式将物理计算分割为一些虚拟的进程,并给予每个执行程序一定量的计算能力.此外操 ... 
- 四、python之 if while for
			一.if条件判断 if 条件判断: 逻辑操作…… …… else: 逻辑操作…… 其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围. ... 
- Educational Codeforces Round 11 E. Different Subsets For All Tuples 动态规划
			E. Different Subsets For All Tuples 题目连接: http://www.codeforces.com/contest/660/problem/E Descriptio ... 
- HDU 5644 King's Pilots 费用流
			King's Pilots 题目连接: http://acm.hdu.edu.cn/showproblem.php?pid=5644 Description The military parade w ... 
- busdog is a filter driver for MS Windows (XP and above) to sniff USB traffic.
			https://code.google.com/p/busdog/ busdog is a filter driver for MS Windows (XP and above) to sniff U ... 
- 无线遥控器方案 Si4010/Si4012
			Si4010包含一个嵌入式兼容8051微控制器(MCU),内具4 kB的RAM.8 kB的一次性编程(OTP)非易失性内存.一个128位EEPROM以及用于函数库(library)功能的12 kB R ... 
- [制作实践]一种基于LM2576的多功能开关电源设计
			http://bbs.kechuang.org/read-kc-tid-9837-page-e.html 摘要:本文介绍了一种性价比高.功能丰富的程控开关电源的设计,对基于LM2576控制核心的升.降 ... 
- 原生JavaScript---正则表达式
			JavaScript 中正则的性能比想象中的低很多.能用字符串方法搞定的,尽量别用正则.------玉伯 抛开性能不谈,一起来看看正则表达式怎么用吧! 先看看JavaScript正则表达式中一些特殊字 ... 
- MAC 更新SVN到1.8
			经过谷歌和百度N次后,最终搞定SVN的升级,Intellij Idea和Xcode5.1都能够正常使用. 步骤: 1. 下载Subverion的Max安装版.(推荐.使用其它brew和port都试过, ... 
- Fiddler2 中文手册
			原文:http://blog.sina.com.cn/s/blog_66a13b8f0100vgfi.html 最近一阵研究 Fiddler2 的使用来着,一开始看起来有点找不着北,索性就根据官网资料 ... 
