Android---58---初学GPS定位
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定位的更多相关文章
- Android下实现GPS定位服务
1.申请Google API Key,参考前面文章 2.实现GPS的功能需要使用模拟器进行经纬度的模拟设置,请参考前一篇文章进行设置 3.创建一个Build Target为Google APIs的项目 ...
- Android入门之GPS定位详解
一.LocationManager LocationMangager,位置管理器.要想操作定位相关设备,必须先定义个LocationManager. LocationManger locationMa ...
- android模拟器使用gps定位
在模拟器上获取GPS信息时,使用Location loc = LocationManager.getLastKnownLocation("gps");来获取location信息,但 ...
- [置顶]
xamarin android使用gps定位获取经纬度
看了文章你会得出以下几个结论 1.android定位主要有四种方式GPS,Network(wifi定位.基站定位),AGPS定位 2.绝大部分android国产手机使用network进行定位是没有作用 ...
- android 获取GPS定位
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xm ...
- Android中通过GPS或NetWork获取当前位置的经纬度
今天在Android项目中要实现一个通过GPS或NetWork来获取当前移动终端设备的经纬度功能.要实现该功能要用到Android Framework 中的 LocationManager 类.下面我 ...
- Android中GPS定位的简单应用
在Android中通过GPS获得当前位置,首先要获得一个LocationManager实例,通过该实例的getLastKnownLocation()方法获得第一个的位置,该方法的说明如下: void ...
- Android开发之位置定位详解与实例解析(GPS定位、Google网络定位,BaiduLBS(SDK)定位)
在android开发中地图和定位是很多软件不可或缺的内容,这些特色功能也给人们带来了很多方便.定位一般分为三种发方案:即GPS定位.Google网络定位以及基站定位 最简单的手机定位方式当然是通过GP ...
- Android GPS定位测试(附效果图)
今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整 ...
- Android GPS定位测试(附效果图)
今天因为工作需要,把以前编写的一个GPS测试程序拿出来重新修改了一下.这个程序说起来有些历史了,是我11年编写的,那时候学了Android开发没多久,算是一个实验性的作品.现在工作需要,重新拿出来修整 ...
随机推荐
- 用DataReader 分页与几种传统的分页方法的比较
对于数据库的分页,目前比较传统的方法是采用分页存储过程,其实用 DataReader 也可以实现分页,不需要写存储过程,实现效率上也比几种比较流行的分页方法要略快. 在开始这个方法之前,让我们先创建一 ...
- vs2017 visual studio2017 密钥 激活码
企业版Enterprise: NJVYC-BMHX2-G77MM-4XJMR-6Q8QF 专业版Professional: KBJFW-NXHK6-W4WJM-CRMQB-G3CDH
- string 字符串--------redis
APPEND 语法:APPEND KEY VALUE 如果key已经存在并且是一个字符串,append 命令将value追加到key原来的值的末尾. 如果key不存在,append就简单地将给定key ...
- 荷兰国旗问题、快排以及BFPRT算法
荷兰国旗问题 给定一个数组arr,和一个数num,请把小于num的数放数组的左边,等于num的数放在数组的中间,大于num的数放在数组的右边.要求额外空间复杂度O(1),时间复杂度O(N). 这个问题 ...
- vue启动
首先在终端terminal连上npm 镜像库 npm config set registry https://registry.npm.taobao.orgnpm installnpm run loc ...
- ERROR: Field 'PostId' doesn't have a default value Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not execute statement
例子: Post p = new Post(); p.setPostId(3); p.setPostName("技术"); 在执行数据保持时提示session.save(p); 的 ...
- 前端安全 xss
整体的 XSS 防范是非常复杂和繁琐的,不仅需要在全部需要转义的位置,对数据进行对应的转义.而且要防止多余和错误的转义,避免正常的用户输入出现乱码. 虽然很难通过技术手段完全避免 XSS,但可以总结以 ...
- videojs
<link href="http://vjs.zencdn.net/5.5.3/video-js.css" rel="stylesheet"> &l ...
- [USACO] 奶牛零食 Treats for the Cows
题目描述 约翰经常给产奶量高的奶牛发特殊津贴,于是很快奶牛们拥有了大笔不知该怎么花的钱.为此,约翰购置了N(1≤N≤2000)份美味的零食来卖给奶牛们.每天约翰售出一份零食.当然约翰希望这些零食全部售 ...
- ubuntu 常见的操作命令
原博客地址为:https://blog.csdn.net/qq_33421080/article/details/76551554 1.cd命令: cd:切换到当前用户根目录,默认[/home/用户名 ...