GPS英文是Global Positioning System 全球定位系统的简称。

Android为GPS功能支持专门提供了一个LocationManager,位置管理器。全部GPS定位相关的服务、对象都将由该对象产生。

获取LocationManager实例:

LocationManager lm = (LocationManager)getSystemService (Context.LOCATION_SERVICE)

三个核心API:LocationManager、LocationProvider、Location

LocationManager提供例如以下方法:

boolean addGpsStatusListener(GpsStatus.Listener listener):加入一个监听GPS状态的监听器;

void addProximityAlert(double latitude,double longitude,float radius,long expiration,PendingIntent intent):加入一个临近警告;

List getAllProviders():获取全部的LocationProvider列表;

String getBestProvider(Criteria criteria,boolean enabledOnly):依据制定条件返回最优的LocationProvider对象。

GpsStatus getGpsStatus(GpsStatus status):获取GPS状态;

Location getLastKnownLocation(String provider):依据LocationProvider获取近期一次已知的Location;

LocationProvider getProvider(String name):依据名称来获取LocationProvider;

List getProviders(Criteria criteria,boolean enabledOnly):依据制定条件获取满足条件的所有LocationProvier的名称;


List getProviders(boolean enabledOnly):获取全部可用的LocationProvider;

boolean isProviderEnabled(String provider):推断制定名称的LocationProvider是否可用。

void removeGpsStatusListener(GpsStatus.Listener listener):删除GPS状态监听器。

void removeProximityAlert(PendingIntent intent):删除一个趋近警告。

void requestLocationUpdates(String provider,long minTime,float minDistance,PendingIntent intent):通过指定的LocationProvider周期性获取定位信息。并通过Intent启动对应的组件;

void requestLocationUpdates(String provider,long minTime,float minDistance,LcoationListener listener):通过指定的LocationProvider周期性的获取定位信息。并触发listener相应的触发器。

LocationProvider类

定位组件的抽象标识,通过它能够获取定位的相关信息。

提供例如以下经常用法:

String getName():返回该LocationProvider的名称;

int getAccuracy():返回该LocationProvider的精度;

int getPowerRequirement():返回该LocationProvider的电源需求;

boolean hasMonetaryCost():返回LocationProvider是收费还是免费;

boolean meetsCriteria(Criteria criteria):推断该LocationProvider是否满足Criteria条件。

boolean requiresCell():推断该LocationProvider是否须要訪问网路基站;

boolean requiresNetword():推断该LocationProvider是否须要网路数据;

boolean requiresStatellite():推断该LocationProvider是否须要訪问卫星的定位系统。

boolean supportsAltitude():推断该LocationProvider是否支持高度信息;

boolean supportsBearing():推断该LocationProvider是否支持方向信息;

boolean supportsSpeed():推断该LocationProvider是否支持速度信息;

LocationListener:位置监听器,监听位置变化,监听设备开关与状态

Location类

代表位置信息的抽象类;

提供例如以下方法来获取定位信息:

float getAccuracy():获取定位信息的精度。

double getAltitude():获取定位信息的高度;

float getBearing():获取定位信息的方向;

double getLatitude():获取定位信息的经度。

double getLongitude():获取定位信息的纬度;

String getProvider():获取提供该定位信息的LocationProvider;

float getSpeed():获取定位信息的速度;

boolean hasAccuracy():推断该定位信息是否有经度信息。

boolean hasAltitude():推断定位信息是否有高度信息;

boolean hasBearing():推断定位信息是否有方向信息;

boolean hasSpeed():推断定位信息是否有速度信息;

LocationListener:位置监听器,监听位置变化。监听设备开关与状态

步骤:

1.获取系统的LocationManager对象

2.使用LocationManager,通过指定LocationProvider来获取定位信息,定位信息由Location对象来表示

3.从Location对象中获取定位信息

以下是几个样例:

1.获取全部可用的LocationProvider:

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.allproviderstest.AllProvidersTest" > <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/providerList" /> <ListView
android:id="@+id/providers"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView> </LinearLayout>

Activity:

public class AllProvidersTest extends Activity {

	ListView providers;
LocationManager lm; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_providers_test);
providers = (ListView) findViewById(R.id.providers);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); List<String> providerNames = lm.getAllProviders();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, providerNames); providers.setAdapter(adapter);
}
}

模拟器中全部可用的LocationProvider有两个:

passive:由LocationProvider.PASSIVE_PROVIDER常量表示

gps:由LocationProvider.GPS_PROVIDER常量表示。

代表通过GPS获取定位信息的LocationProvider对象

另一个名为network的LocationProvider,由LocationProvider.NETWORK_PROVIDER常量表示。

代表通过移动通信网络获取定位信息的LocationProvider对象。

2.通过名称来获取指定的LocationProvider:

比如:

获取基于GPS的LocationProvider:

LocationProvider locProvider = lm.getProvider(LocationManager.GPS_PROVIDER)

依据Criteria获得LocationProvider:

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.freeproviderstest.FreeProvidersTest" > <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/providerList" /> <ListView
android:id="@+id/providers"
android:layout_width="fill_parent"
android:layout_height="fill_parent" /> </LinearLayout>

Activity:

public class FreeProvidersTest extends Activity {

	ListView providers;
LocationManager lm; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_free_providers_test); providers = (ListView) findViewById(R.id.providers);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // 创建一个LocationProvider的过滤条件
Criteria cri = new Criteria();
// 设置要求LocationProvider必须是免费的。
cri.setCostAllowed(false);
// 设置要求LocationProvider能提供高度信息
cri.setAltitudeRequired(true);
// 设置要求LocationProvider能提供方向信息
cri.setBearingRequired(true);
// 获取系统全部复合条件的LocationProvider的名称
List<String> providerNames = lm.getProviders(cri, false);
System.out.println(providerNames.size());
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, providerNames);
// 使用ListView来显示全部可用的LocationProvider
providers.setAdapter(adapter);
}
}

3.

获取定位数据:

通过模拟器发送GPS信息:

启动模拟器之后,在DDMS下的Emulator Control 面板就可以发送GPS定位信息。

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.locationtest.LocationTest" > <EditText
android:id="@+id/show"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:editable="false" /> </LinearLayout>

Activity:

public class LocationTest extends Activity {

	// 定义LocationManager对象
LocationManager locManager;
// 定义程序界面中的EditText组件
EditText show; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_test); show = (EditText) findViewById(R.id.show);
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 从GPS获取近期的近期的定位信息
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// 使用location依据EditText的显示
updateView(location);// 设置每3秒获取一次GPS的定位信息
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000,
8, new LocationListener() // ①
{
@Override
public void onLocationChanged(Location location) {
// 当GPS定位信息发生改变时,更新位置
updateView(location);
} @Override
public void onProviderDisabled(String provider) {
updateView(null);
} @Override
public void onProviderEnabled(String provider) {
// 当GPS LocationProvider可用时。更新位置
updateView(locManager.getLastKnownLocation(provider));
} @Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
});
} // 更新EditText中显示的内容
public void updateView(Location newLocation) {
if (newLocation != null) {
StringBuilder sb = new StringBuilder();
sb.append("实时的位置信息:\n");
sb.append("经度:");
sb.append(newLocation.getLongitude());
sb.append("\n纬度:");
sb.append(newLocation.getLatitude());
sb.append("\n高度:");
sb.append(newLocation.getAltitude());
sb.append("\n速度:");
sb.append(newLocation.getSpeed());
sb.append("\n方向:");
sb.append(newLocation.getBearing());
show.setText(sb.toString());
} else {
// 假设传入的Location对象为空则清空EditText
show.setText("");
}
}
}

4.

临近警告:

通过LocationManager.addProximityAlert(double latitude,double longitude , float radius , long expiration ,PendingIntent intent)加入一个临近警告

參数:

latitude:指定固定点的经度

longitude:指定固定点的纬度

radius:半径长度

expiration:该參数指定经过多少毫秒后该临近警告就会过期失效

intent:该參数指定临近该固定点时出发该intent相应的组件。

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.proximitytest.ProximityTest" > <TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" /> </LinearLayout>

Activity:

public class ProximityTest extends Activity {

	@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_proximity_test);
// 定位服务常量
String locService = Context.LOCATION_SERVICE;
// 定位服务管理器实例
LocationManager locationManager;
// 通过getSystemService方法获得LocationManager实例
locationManager = (LocationManager) getSystemService(locService);
// 定义山东淄博的大致经度、纬度
double longitude = 117.3;
double latitude = 36.5;
// 定义半径(5公里)
float radius = 5000;
// 定义Intent
Intent intent = new Intent(this, ProximityAlertReciever.class);
// 将Intent包装成PendingIntent
PendingIntent pi = PendingIntent.getBroadcast(this, -1, intent, 0);
// 加入临近警告
locationManager.addProximityAlert(latitude, longitude, radius, -1, pi);
}
}

ProximityAlertReciever:

public class ProximityAlertReciever extends BroadcastReceiver {

	@Override
public void onReceive(Context context, Intent intent) {
// 获取是否为进入指定区域
boolean isEnter = intent.getBooleanExtra(
LocationManager.KEY_PROXIMITY_ENTERING, false);
if (isEnter) {
// 显示提示信息
Toast.makeText(context, "您已经进入广州天河区", Toast.LENGTH_LONG).show();
} else {
// 显示提示信息
Toast.makeText(context, "您已经离开广州天河区", Toast.LENGTH_LONG).show();
}
}
}

Android---58---初学GPS定位的更多相关文章

  1. Android下实现GPS定位服务

    1.申请Google API Key,参考前面文章 2.实现GPS的功能需要使用模拟器进行经纬度的模拟设置,请参考前一篇文章进行设置 3.创建一个Build Target为Google APIs的项目 ...

  2. Android入门之GPS定位详解

    一.LocationManager LocationMangager,位置管理器.要想操作定位相关设备,必须先定义个LocationManager. LocationManger locationMa ...

  3. android模拟器使用gps定位

    在模拟器上获取GPS信息时,使用Location loc = LocationManager.getLastKnownLocation("gps");来获取location信息,但 ...

  4. [置顶] xamarin android使用gps定位获取经纬度

    看了文章你会得出以下几个结论 1.android定位主要有四种方式GPS,Network(wifi定位.基站定位),AGPS定位 2.绝大部分android国产手机使用network进行定位是没有作用 ...

  5. android 获取GPS定位

    AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xm ...

  6. Android中通过GPS或NetWork获取当前位置的经纬度

    今天在Android项目中要实现一个通过GPS或NetWork来获取当前移动终端设备的经纬度功能.要实现该功能要用到Android Framework 中的 LocationManager 类.下面我 ...

  7. Android中GPS定位的简单应用

    在Android中通过GPS获得当前位置,首先要获得一个LocationManager实例,通过该实例的getLastKnownLocation()方法获得第一个的位置,该方法的说明如下: void ...

  8. Android开发之位置定位详解与实例解析(GPS定位、Google网络定位,BaiduLBS(SDK)定位)

    在android开发中地图和定位是很多软件不可或缺的内容,这些特色功能也给人们带来了很多方便.定位一般分为三种发方案:即GPS定位.Google网络定位以及基站定位 最简单的手机定位方式当然是通过GP ...

  9. Android GPS定位测试(附效果图)

    今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整 ...

  10. Android GPS定位测试(附效果图)

    今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整 ...

随机推荐

  1. 微信关于网页授权access_token和普通access_token的区别

    微信官网网址:https://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html#.E9.99.84.EF.BC.9A.E6. ...

  2. 由DB2分页想到的,关于JDBC ResultSet 处理大数据量

    最近在处理DB2 ,查询中,发现如下问题.如果一个查询 count(*),有几十万行,分页如何实现 select row_number() over (order by fid desc ) as r ...

  3. Farseer.net轻量级开源框架 中级篇:执行SQL语句

    导航 目   录:Farseer.net轻量级开源框架 目录 上一篇:Farseer.net轻量级开源框架 中级篇: 事务的使用 下一篇:Farseer.net轻量级开源框架 中级篇: DbFacto ...

  4. struts2特殊符号替换

    今天用struts2做了一个小例子,结果发现个问题 action代码如下 private String table; public String execute(){ setName("pe ...

  5. 15年第六届蓝桥杯第七题_(string)

    手链样式 小明有3颗红珊瑚,4颗白珊瑚,5颗黄玛瑙.他想用它们串成一圈作为手链,送给女朋友.现在小明想知道:如果考虑手链可以随意转动或翻转,一共可以有多少不同的组合样式呢? 请你提交该整数.不要填写任 ...

  6. 第三节:执行一些EF的增删改查

    针对两表操作 一丶增加 #region 05-增加操作 /// <summary> /// 05-增加操作 /// </summary> /// <param name= ...

  7. Ajax 调用案例及错误捕捉

    function postFunc() { var scoreResultStr = readyData(); $.ajax({ type: "post", url: " ...

  8. ExtJs如何判断form表单是否被修改过详解

    1.Extjs表单提交主要有三种方式: 1, EXT的form表单ajax提交(默认提交方式)      相对单独的ajax提交来说优点在于能省略写参数数组 ,form.getForm().submi ...

  9. C. Day at the Beach

    codeforces 599c C. Day at the Beach One day Squidward, Spongebob and Patrick decided to go to the be ...

  10. Maven_真的需要吗?

    1.真的需要吗? Maven 是干什么用的?这是很多同学在刚开始接触 Maven 时最大的问题.之所以会提出这个问题,是因为即使不使用 Maven 我们仍然可以进行 B/S 结构项目的开发.从表述层. ...