Android定位主要使用的是基于位置服务(Location Based Service)技术,有了 Android 系统作为载体,我们可以利用定位出的位置进行许多丰富多彩的操作,比如定位城市,根据我们当前的位置,查找要去的目的地的路线等等,因此,现在几乎开发的每一款互联网app产品都有定位功能,好了,现在我们开始学习简单的定位。

效果图:

代码:

activity_main.xml中的代码:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/position_text"android:layout_width="wrap_content"android:layout_height="wrap_content" android:textSize="20sp"android:text="经纬度"/><TextViewandroid:id="@+id/tipInfo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="提示信息" /></LinearLayout>

MainActivity.java中的代码:

package com.test.locationdemo;import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;public class MainActivity extends Activity {private TextView positionText;// 存放经纬度的文本private TextView tipInfo;// 提示信息private LocationManager locationManager;// 位置管理类private String provider;// 位置提供器SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);positionText = (TextView) findViewById(R.id.position_text);tipInfo = (TextView) findViewById(R.id.tipInfo);// 获得LocationManager的实例locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);// 获取所有可用的位置提供器List<String> providerList = locationManager.getProviders(true);if (providerList.contains(LocationManager.GPS_PROVIDER)) {//优先使用gpsprovider = LocationManager.GPS_PROVIDER;} else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) {provider = LocationManager.NETWORK_PROVIDER;} else {// 没有可用的位置提供器Toast.makeText(MainActivity.this, "没有位置提供器可供使用", Toast.LENGTH_LONG).show();return;}Location location = locationManager.getLastKnownLocation(provider);if (location != null) {// 显示当前设备的位置信息String firstInfo = "第一次请求的信息";showLocation(location, firstInfo);} else {String info = "无法获得当前位置";Toast.makeText(this, info, 1).show();positionText.setText(info);}// 更新当前位置locationManager.requestLocationUpdates(provider, 10 * 1000, 1,locationListener);}protected void onDestroy() {super.onDestroy();if (locationManager != null) {// 关闭程序时将监听器移除locationManager.removeUpdates(locationListener);}};LocationListener locationListener = new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {// TODO Auto-generated method stub}@Overridepublic void onProviderEnabled(String provider) {// TODO Auto-generated method stub}@Overridepublic void onProviderDisabled(String provider) {// TODO Auto-generated method stub}@Overridepublic void onLocationChanged(Location location) {// 设备位置发生改变时,执行这里的代码String changeInfo = "隔10秒刷新的提示:\n 时间:" + sdf.format(new Date())+ ",\n当前的经度是:" + location.getLongitude() + ",\n 当前的纬度是:"+ location.getLatitude();showLocation(location, changeInfo);}};/*** 显示当前设备的位置信息* * @param location*/private void showLocation(Location location, String changeInfo) {// TODO Auto-generated method stubString currentLocation = "当前的经度是:" + location.getLongitude() + ",\n"+ "当前的纬度是:" + location.getLatitude();positionText.setText(currentLocation);tipInfo.setText(changeInfo);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}}

AndroidManifest.xml中的代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.test.locationdemo"android:versionCode="1"android:versionName="1.0" ><uses-sdkandroid:minSdkVersion="14"android:targetSdkVersion="18" /><!--获取设备当前位置的权限 --><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><applicationandroid:allowBackup="true"android:icon="@drawable/ic_launcher"android:label="@string/app_name"android:theme="@style/AppTheme" ><activityandroid:name="com.test.locationdemo.MainActivity"android:label="@string/app_name" ><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

项目demo下载:

Android定位功能小项目下载

理论讲解:

Android的定位功能使用的技术是:基于位置的服务(Location Based Service)。

以上定位功能实现的步骤如下:

1、获得LocationManager的实例

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

2、使用位置提供器,确定当前Android设备的位置

Android中有三种位置提供器,分别是:
a、GPS_PROVIDER:使用GPS定位,精准度比较高,但是非常耗电;
b、NETWORK_PROVIDER:使用网络定位,精准度稍差,但是耗电量比较小;
c、PASSIVE_PROVIDER:很少使用(可以暂不考虑)

3、将选择好的位置提供器传入到getLastKnownLocation方法中,就可以得到一个Location对象
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
这个 Location 对象中包含了经度、纬度、海拔等一系列的位置信息。

4、当设备位置发生改变的时候获取到最新的位置信息,使用LocationManager 的 requestLocationUpdates()方
法,同时接收四个参数,分别是:
第一个参数是位置提供器的类型;
第二个参数是监听位置变化的时间间隔,以毫秒为单位;
第三个参数是监听位置变化的距离间隔,以米为单位;
第四个参数则是 LocationListener监听器。

代码如下:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10,new LocationListener() {@Overridepublic void onStatusChanged(String provider, int status, Bundle extras) {}@Overridepublic void onProviderEnabled(String provider) {}@Overridepublic void onProviderDisabled(String provider) {}@Overridepublic void onLocationChanged(Location location) {//设备位置发生改变的时候,执行这里的代码}
});

代码解释:LocationManager每隔5秒钟(第二个参数)会检测一下位置的变化情况,当移动距离超过 10米(第三个参数)的时候,
就会调用 LocationListener的 onLocationChanged()方法,并把新的位置信息作为参数传入。

获取设备当前的位置信息是要声明权限的, 在AndroidManifest.xml中添加代码:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationtest"
android:versionCode="1"
android:versionName="1.0" >
……
<!--获取设备当前位置的权限 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
……
</manifest>

--------------------------------------------------------------------------------------------------------------------------------------------------

上面的定位有问题,补充一个最新的demo如下:

最近有朋友提出上面这个demo下载下来不能够定位,给想使用定位的朋友造成了困惑,再此表示抱歉,由于上面的步骤写的还是很详细的,所以,上面的就不改了,把最新的定位代码放到下面,作为补充。

下面这个代码的功能是:

用来获得定位信息,然后定时传给服务器做记录的,这个定位是直接使用gps定位的,gps在建筑物里或建筑物几种的地方,信息不太好,到了屋外一般信息还是很强的。能同时获得几十甚至几百个卫星定位

想使用的朋友可以按照自己的业务需求改一下,

MainActivity代码:

package com.example.gpsactivity;import java.text.SimpleDateFormat;
import java.util.Date;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;public class MainActivity extends Activity {private TextView logText;private TextView currentTime;private TextView urlInfoId;private TextView resultInfoId;private TextView editUrl;private TextView editTime;private Button commitBtn;private LocationManager lm;private static final String TAG = "MainActivity";private long minTime = 1000 * 5;private float minDistance = 0;private static int period = 1000 * 5; // 5sprivate String url = "";// 提交的接口urlprivate long lastMillis = 0;// 上一次提交的时间private String longitude = ""; // 经度private String latitude = ""; // 维度SimpleDateFormat format = new SimpleDateFormat("yyyy年mm月dd日 HH:mm:ss");@Overrideprotected void onDestroy() {super.onDestroy();lm.removeUpdates(locationListener);}private void setLog(String txt) {setLogInfo(txt);}private void setLogInfo(String txt) {logText.setText("\n当前时间:" + format.format(new Date()) + "\n" + txt);}@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.gps_demo);currentTime = (TextView) this.findViewById(R.id.currentTime);urlInfoId = (TextView) this.findViewById(R.id.urlInfoId);resultInfoId = (TextView) this.findViewById(R.id.resultInfoId);logText = (TextView) this.findViewById(R.id.logText);editUrl = (TextView) findViewById(R.id.editUrlId);editTime = (TextView) findViewById(R.id.editTimeId);commitBtn = (Button) findViewById(R.id.commitId);getLocation();/*** 提交*/commitBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {String m = "";url = editUrl.getText().toString();if (!"".equals(url)) {url = url + "&lgt=${lgt}&lat=${lat}";m = "提交url是:" + url + "\n";}String time = editTime.getText().toString();if (!"".equals(time) && time != null) {boolean isNum = time.matches("[0-9]+");if (isNum) {period = Integer.valueOf(time) * 1000;m = m + "时间间隔是:" + editTime.getText().toString() + "秒";}}if (!"".equals(m)) {Toast.makeText(MainActivity.this, m, Toast.LENGTH_LONG).show();}}});}private void getLocation() {lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);// 判断GPS是否正常启动if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {Toast.makeText(this, "请开启GPS导航...", Toast.LENGTH_SHORT).show();setLog("请开启GPS导航...");// 返回开启GPS导航设置界面Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);startActivityForResult(intent, 0);return;}// 为获取地理位置信息时设置查询条件String bestProvider = lm.getBestProvider(getCriteria(), true);// 获取位置信息// 如果不设置查询要求,getLastKnownLocation方法传人的参数为LocationManager.GPS_PROVIDERLocation 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(),更新位置*/if (lm.getProvider(LocationManager.GPS_PROVIDER) != null) {Log.d("GPS_PROVIDER执行:", "GPS方法执行。。。。。。。。");lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime,minDistance, locationListener);} else if (lm.getProvider(LocationManager.NETWORK_PROVIDER) != null) {Log.d("NETWORK执行:", "NETWORK方法执行。。。。。。。。");lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,minTime, minDistance, locationListener);}}// 位置监听private LocationListener locationListener = new LocationListener() {/*** 位置信息变化时触发*/public void onLocationChanged(Location location) {setLog("经度:" + location.getLongitude() + "\n纬度:"+ location.getLatitude());updateView(location);}/*** GPS状态变化时触发*/public void onStatusChanged(String provider, int status, Bundle extras) {switch (status) {// GPS状态为可见时case LocationProvider.AVAILABLE:Log.i(TAG, "当前GPS状态为可见状态");setLog("当前GPS状态为可见状态");break;// GPS状态为服务区外时case LocationProvider.OUT_OF_SERVICE:Log.i(TAG, "当前GPS状态为服务区外状态");setLog("当前GPS状态为服务区外状态");break;// GPS状态为暂停服务时case LocationProvider.TEMPORARILY_UNAVAILABLE:Log.i(TAG, "当前GPS状态为暂停服务状态");setLog("当前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, "第一次定位");setLog("第一次定位");break;// 卫星状态改变case GpsStatus.GPS_EVENT_SATELLITE_STATUS:long currenMillis = System.currentTimeMillis();// 当前时间if ((currenMillis - lastMillis) > period) {uploadUrl();lastMillis = currenMillis;// 获取当前状态GpsStatus gpsStatus = lm.getGpsStatus(null);// 获取卫星颗数的默认最大值int maxSatellites = gpsStatus.getMaxSatellites();// 创建一个迭代器保存所有卫星Iterator<GpsSatellite> iters = gpsStatus.getSatellites().iterator();int count = 0;while (iters.hasNext() && count <= maxSatellites) {count++;}Log.i(TAG, "卫星状态改变,搜索到:" + count + "颗卫星");setLog("卫星状态改变,搜索到:" + count + "颗卫星 \n经度:" + longitude+ "\n纬度:" + latitude);}break;// 定位启动case GpsStatus.GPS_EVENT_STARTED:Log.i(TAG, "定位启动");setLog("定位启动");break;// 定位结束case GpsStatus.GPS_EVENT_STOPPED:Log.i(TAG, "定位结束");setLog("定位结束");break;}}private void uploadUrl() {if (!"".equals(url) && url != null) {if (!"".equals(longitude) && !"".equals(latitude)) {uploadHttp();}}};};/*** 实时更新文本内容* * @param location*/private void updateView(Location location) {if (location != null) {longitude = String.valueOf(location.getLongitude());latitude = String.valueOf(location.getLatitude());Log.i(TAG, String.valueOf(location.getLongitude()));} else {Log.i(TAG, "未获取");}// editText.append("\n更新时间:" + new Date());}private void uploadHttp() {url = url.replace("${lgt}", longitude).replace("${lat}", latitude);urlInfoId.setText(url);HttpUtils http = new HttpUtils();http.send(HttpMethod.GET, url, new RequestCallBack<String>() {@Overridepublic void onFailure(HttpException arg0, String arg1) {resultInfoId.setText("失败:\n" + arg1);}@Overridepublic void onSuccess(ResponseInfo<String> arg0) {currentTime.setText("当前时间是:" + format.format(new Date()));resultInfoId.setText("成功:\n"+arg0.result);}});}/*** 返回查询条件* * @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;}}

gps_demo.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent" ><LinearLayoutandroid:layout_width="fill_parent"android:layout_height="fill_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/logText"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginBottom="25px"android:layout_marginTop="15px"android:background="#F0E68C"android:minHeight="100dp"android:text="显示定位坐标信息" /><EditTextandroid:id="@+id/editUrlId"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="输入接口地址" ></EditText><EditTextandroid:id="@+id/editTimeId"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="输入时间间隔(如1秒,输入1),默认5秒" /><Buttonandroid:id="@+id/commitId"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="提交" /><TextViewandroid:id="@+id/currentTime"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="20px"android:background="#FFFFE0"android:text="时间" /><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="15px"android:text="提交地址信息:" /><TextViewandroid:id="@+id/urlInfoId"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="15px"android:background="#71C671" /><TextViewandroid:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginTop="20px"android:text="返回信息:" /><TextViewandroid:id="@+id/resultInfoId"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_marginBottom="50px"android:layout_marginTop="20px"android:background="#F08080" /></LinearLayout></ScrollView>

项目demo下载地址:

app定位+定时提交坐标信息到服务器(新)

android定位:获取当前位置的经纬度相关推荐

  1. Android之获取当前位置的经纬度

    Android之 点击按钮获取当前位置的经纬度 过几秒更新当前位置的经纬度 https://upload-images.jianshu.io/upload_images/13225108-85f1bc ...

  2. Android之获取网络位置的经纬度

    上一篇已经说了一下基于位置的服务~ 这一篇想说一下基于网络的位置提供者获取到经纬度 直接贴代码吧,我是获取了聚合数据的位置,然后在获取到经纬度的, 其实也可以获取到自己位置的经纬度,那就是基于GPS的 ...

  3. android网络获取经纬,Android中透过GPS或NetWork获取当前位置的经纬度

    Android中通过GPS或NetWork获取当前位置的经纬度 private double latitude=0.0; private double longitude =0.0; Location ...

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

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

  5. html5经纬度定位 源码_HTML5教程 如何获取当前位置的经纬度

    本篇教程探讨了HTML5教程 如何获取当前位置的经纬度,希望阅读本篇文章以后大家有所收获,帮助大家HTML5+CSS3从入门到精通 . < 是想让地图的定位用户位置更准确一些. 查看了介绍: h ...

  6. html调用腾讯地图定位当前位置,vue web项目中调用腾讯地图API获取当前位置的经纬度...

    vue web项目中调用腾讯地图API获取当前位置的经纬度 vue web项目中调用腾讯地图API获取当前位置的经纬度 在main.js 中添加一下代码 import axios from 'axio ...

  7. vue3定位当前位置,获取当前位置的经纬度

    vue3定位当前位置,获取当前位置的经纬度 注意事项(访问地址必须是https) 获取当前位置经纬度 注意事项(访问地址必须是https) 在vue.config.js文件内设置https:true, ...

  8. android 逆地址,Android高德获取逆地址编码(经纬度坐标-地址描述如省市区街道)

    Android高德获取逆地址编码(经纬度坐标-地址描述如省市区街道) 可以在非地图视图下直接获取,只要传入当前位置的经纬度 当然也可以在地图模式下获取详细信息 在非第三方地图集成下(系统自带功能)获取 ...

  9. android自动获取位置,Android中获取当前位置信息

    这篇教程主要介绍了在Android平台上如何使用服务完成定位功能.众所周知,Android设备的当前位置信息,对开发创新性App.解决人们日常生活问题有极大帮助.在Android平台开发定位相关的应用 ...

  10. UWP Windows10开发获取设备位置(经纬度)

    UWP Windows10开发获取设备位置(经纬度) 原文:UWP Windows10开发获取设备位置(经纬度) 1.首先要在UWP项目的Package.appxmanifest文件中配置位置权限,如 ...

最新文章

  1. 管理员技术(六): 硬盘分区及格式化、 新建一个逻辑卷、调整现有磁盘的分区、扩展逻辑卷的大小、添加一个swap分区...
  2. 【OpenCV 4开发详解】漫水填充法
  3. .Net WEB打印需要设置的内容和方法
  4. 微信悄然上线了十款新表情,你注意到了吗?
  5. 帷幕的帷是什么意思_俗语:“宁娶寡妇,不娶生妻!”什么是“生妻”?老祖宗智慧...
  6. promise then err_Promise 原理解析与实现(遵循Promise/A+规范)
  7. 程序员笑话集锦之丈夫与妻子篇
  8. java 图片线条_JAVA 关于JFrame的问题,我的图片会被线条给覆盖住,怎样让图片在上面呢...
  9. html图书借阅源码,图书借阅管理系统代码图书管理系统源代码
  10. VMware虚拟机的下载与安装(附Win10简易安装教程)
  11. Android渐变背景色
  12. php选课实验成品_PHP基于B/S模式下的学生选课管理系统、源码分享
  13. 解决svchost.exe一直运行下载,占网速,关闭成功后再次重复开启,禁止不掉。亲测有效
  14. MacOS 升级自带PHP5.6 升级到 PHP7.1
  15. java中finally语句是否一定会被执行
  16. 刷表法 和 填表法(DP)
  17. 生产制造管理系统MES
  18. 哈佛参考文献注释及APA文献格式介绍
  19. ctfshow_2021月饼杯记录
  20. 虚机安装Linux网络配置的一些笔记(隔离,桥接,NAT)

热门文章

  1. 为什么大家都用美颜SDK进行拍摄?美颜SDK未来的发展方向是什么?
  2. Oracle查询用户权限角色(dba_sys_privs)
  3. 搜狗翻译宝成为官方指定翻译机
  4. 1304 佳佳的斐波那契(矩阵乘法)
  5. Blender基础:多边形建模中F命令和J命令的区别
  6. 服务器域名解析步骤总结
  7. 项目源码+付费进群系统分享
  8. 利用计算机模拟地理实验,虚拟地理实验在中学地理教学的应用论文
  9. 一个手机游戏服务器的架构
  10. SSL/TLS单向认证和双向认证介绍