这是我在CSDN里发表的第一篇博客。

我是在大学期间跟学长一起做项目时开始接触Android的。由于自己有JAVA编程的基础,以及拥有可以测试的Android手机,于是在空闲时间在图书馆阅读android方面的书籍。因为我们的项目是基于定位的,因此免不了要学习定位相关的知识。但是书上讲的内容大多都是理论上的,对于刚刚接触android的新手来说存在很多的困难。于是我求助于CSDN各位大神的博客,把代码都运行了一遍,然后编写了自己的基于GPS定位的代码。菜鸟写的代码,肯定很多不足的地方,希望大家给出意见。

现在的智能手机大多数都有GPS模块,和NETWORK相比,GPS定位更加精确(小数点后8位),并且不耗费流量。但缺点是耗电大,只能在户外有效,另外手机的GPS通常是关闭的,并且首次定位时间过长(最长的大概几分钟)。虽然这样,考虑到手机流量的问题以及精确度,我还是觉得有必要自己尝试一下。

我们所用到的核心类是这3个: android.location.LocationManager , android.location.Location , android.location.LocationListener

我们知道,LocationManager位于应用框架层,那么我们如何能够得到这个对象的实例呢?和其他系统服务一样,我们可以通过这样的一种方式得到该对象的实例:

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

首先新建一个名为GPSLOCATION的工程(Target 为 android API 8)。

工程目录结构如下:


利用GPS定位[android]_第1张图片


















然后修改/res/layout/main.xml,代码如下:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:id="@+id/msg"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />    <TextView        android:id="@+id/status"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="GPS当前状态:搜索中..." />    <TextView        android:id="@+id/tv"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="正在定位,请稍候..." />    <TextView        android:id="@+id/help"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="Hint:必须将手机移至户外,GPS不耗费流量" /></LinearLayout>


然后我们来看以下MainActivity.java文件,代码如下:


package zjut.tsw.location;import android.app.Activity;import android.content.Context;import android.graphics.Color;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.location.LocationProvider;import android.os.Bundle;import android.widget.TextView;public class MainActivity extends Activity implements LocationListener {private TextView tv, msg, status;private double longitude = 0.0;private double latitude = 0.0;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);// 获得TextView对象tv = (TextView) findViewById(R.id.tv);status = (TextView) findViewById(R.id.status);msg = (TextView) findViewById(R.id.msg);// 获得LocationManager实例LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);// 如果GPS已打开if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {msg.setText("GPS开关状态:enabled");// 注册位置监听器 ,mTime = 3000ms, mDistance = 0lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3 * 1000,0, this);} else {msg.setText("GPS开关状态:disabled");tv.setText("请打开GPS!");}}@Overrideprotected void onPause() {tv.setText("正在定位,请稍候...");super.onPause();}public void onLocationChanged(Location provider) {if (provider != null) {latitude = provider.getLatitude();longitude = provider.getLongitude();tv.setText("纬度:" + latitude + "\n经度:" + longitude);}}public void onProviderDisabled(String provider) {msg.setTextColor(Color.RED);msg.setText(provider.toUpperCase() + "开关状态:disabled");}public void onProviderEnabled(String provider) {msg.setTextColor(Color.GREEN);msg.setText(provider.toUpperCase() + "开关状态:enabled");}public void onStatusChanged(String provider, int sta, Bundle extras) {if (LocationProvider.AVAILABLE == sta) {status.setTextColor(Color.GREEN);status.setText("GPS当前状态:Available");}if (LocationProvider.OUT_OF_SERVICE == sta) {status.setTextColor(Color.RED);status.setText("GPS当前状态:Out of Service");}if (LocationProvider.TEMPORARILY_UNAVAILABLE == sta) {status.setTextColor(Color.YELLOW);status.setText("GPS当前状态:Temporarily unavailable");}}}

最后,别忘了在AndroidManifest.xml中添加必要的权限 :


    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

最后说明一下,第一次用GPS定位时,一般出现这样的问题,即

Locationlocation= lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

我们可能会得到location为null。

官方文档是这样解释的:

publicLocationgetLastKnownLocation(Stringprovider)

Since: API Level 1

Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.

If the provider is currently disabled, null is returned.

大概意思就是说getLastKnownLocation返回的是最后一次知道的提供者给定的地理位置,如果初次使用GPS,那么返回的就应该是空值。



另外说明的是真机测试一定要在户外GPS一定要打开,并且需要等待一定的时间才会返回经纬度。

这里只测试GPS,没有考虑NET_WORK

真机测试过,没有问题,截图如下:(杭州)


利用GPS定位[android]_第2张图片



更多相关文章

  1. Android源码去除状态栏
  2. [置顶] Android实用代码集
  3. Android ViewPager和PagerAdapter简单代码写法
  4. Android新手入门实例之Android漂亮时钟的源代码
  5. 如何实现Android重启应用程序代码 ?
  6. android状态栏透明/白底黑字
  7. android常用的代码片段
  8. Android Camera代码位置

随机推荐

  1. 打开Android Studio报错"required plugin
  2. Android-- Intent.Action(1)
  3. 关于listView设置背景引起StackOverflowE
  4. Android gradle 命令行打包
  5. Android 的EditText实现不可编辑
  6. 【Android】【Lottie】在Android中使用Lo
  7. [导入]Android平台上四种保存数据的方法
  8. android获取屏幕分辨率大小(DisplayMetri
  9. 启动模式详解
  10. android HttpURLConnection 连接网络 读