Android获取当前位置的三种方式及其使用方法

2023-11-17

1.GPS定位 2.基站定位 此类位置的获取有赖于手机无线通讯信号,当手机处在信号覆盖范围内,手机可以获得该区域(即通讯术语中的“小区”)的识别号。因为这些识别号是惟一的,因此可以将识别号和地理坐标对应起来,因此根据识别号就可以知道地理位置。但是误差比较大。 MCC(Mobile Country Code)、MNC(Mobile Network Code)、LAC(Location Aera Code)、CID(Cell Tower ID)是通讯业内的名词。MCC标识国家,MNC标识网络,两者组合起来则唯一标识一家通讯运营商。从维基百科上了解到,一个国家的MCC不唯一,例如中国有460和461,一家运营商也不只一个MNC,例如中国移动有00、02、07。LAC标识区域,类似于行政区域,运营商将大区域划分成若干小区域,每个区域分配一个LAC。CID标识基站,若手机处在工作状态,则必须要和一个通讯基站进行通讯,通过CID就可以确定手机所在的地理范围。 在Android当中,大部分和通讯网络相关的信息都需要经过一项系统服务,即TelephoneManager来获得。
TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String operator = mTelMan.getNetworkOperator();
String mcc = operator.substring(0, 3);
String mnc = operator.substring(3);
GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
int cid = location.getCid();
int lac = location.getLac();
通过上面的方法,可获得MCC、MNC、CID、LAC,对照Geolocation API Network Protocol,剩下不多的参数也可以获得,发起请求后根据响应内容即可得到地理位置信息。 请求(Request)的信息如下:
{"cell_towers":[{"mobile_network_code":"00","location_area_code":9733,
"mobile_country_code":"460","cell_id":17267},{"mobile_network_code":"00","location_area_code":9733,
"mobile_country_code":"460","cell_id":27852},{"mobile_network_code":"00","location_area_code":9733,
"mobile_country_code":"460","cell_id":27215},{"mobile_network_code":"00","location_area_code":9733,
"mobile_country_code":"460","cell_id":27198},{"mobile_network_code":"00","location_area_code":9484,
"mobile_country_code":"460","cell_id":27869},{"mobile_network_code":"00","location_area_code":9508,
"mobile_country_code":"460","cell_id":37297},{"mobile_network_code":"00","location_area_code":9733,
"mobile_country_code":"460","cell_id":27888}],
"host":"maps.google.com",
"version":"1.1.0"}
响应(Response)的信息如下:
{"location":{"latitude":23.12488,"longitude":113.271907,"accuracy":630.0},"access_token":"2:61tEAW-rONCT1_W-:JVpp2_jq5a0L-5JK"}
3.WIFI定位 其原理是首先收集每个WIFI无线接入点的位置,对每个无线路由器进行唯一的标识,在数据库中注明这些接入点的具体位置。 使用时,一旦发现有WI-FI接入点,则进入到数据中查看匹配的记录,进而得到位置信息。 WIFI定位主要取决于节点(node)的物理地址(mac address)。与提供TelephoneManager一样,Android也提供了获取WIFI信息的接口:WifiManager。
WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiMan.getConnectionInfo();
String mac = info.getMacAddress();
String ssid = info.getSSID();
通过上面的方法,即可获得必要的请求参数。 发出的请求(Request)信息如下:
{"wifi_towers":[{"mac_address":"00:23:76:AC:41:5D","ssid":"Aspire-NETGEAR"}],"host":"maps.google.com","version":"1.1.0"}
响应(Response)的信息如下:
{"location":{"latitude":23.129075,"longitude":113.264423,"accuracy":140000.0},"access_token":"2:WRr36ynOz_d9mbw5:pRErDAmJXI8l76MU"}
以上简单介绍了android中获取位置的三种定位方式。 实际开发中可利用android.location中的LocationManager类,该类封装了地理位置信息的接口,提供了GPS_PROVIDER和 NETWORK_PROVIDER。 如果开发的应用需要高精确性,那么可使用GPS_PROVIDER,但这也意味着应用无法在室内使用,待机时间缩短,响应时间稍长等问题; 如果开发的应用需要快速反应,对精度要求不怎么高,并且要尽可能节省电量,那么使用NETWORK_PROVIDER是不错的选择。 这里提一下,还有一个 PASSIVE_PROVIDER,在实际应用中较少使用。 1.如下代码就是设置从Network中获取位置:
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0, mLocLis);
需要对应的权限:android.permission.ACCESS_COARSE_LOCATION 2.如下代码就是设置从GPS获取位置:
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, mLocLis);
需要对应的权限:android.permission.ACCESS_FINE_LOCATION 如果代码里使用了两个 PROVIDER,则只需要一个权限即可:android.permission.ACCESS_FINE_LOCATION。 以下是整个过程的代码:
public class DemoActivity extends Activity {

private static final String TAG = "DemoActivity";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void onRequestLocation(View view) {
switch (view.getId()){
case R.id.gpsBtn:
Log.d(TAG, "GPS button is clicked");
requestGPSLocation();
break;
case R.id.telBtn:
Log.d(TAG, "CellID button is clicked");
requestTelLocation();
break;
case R.id.wifiBtn:
Log.d(TAG, "WI-FI button is clicked");
requestWIFILocation();
break;
case R.id.netBtn:
Log.d(TAG, "Network button is clicked");
requestNetworkLocation();
break;
}
}

private void requestTelLocation() {
TelephonyManager mTelMan = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// MCC+MNC. Unreliable on CDMA networks
String operator = mTelMan.getNetworkOperator();
String mcc = operator.substring(0, 3);
String mnc = operator.substring(3);

GsmCellLocation location = (GsmCellLocation) mTelMan.getCellLocation();
int cid = location.getCid();
int lac = location.getLac();

JSONObject tower = new JSONObject();
try {
tower.put("cell_id", cid);
tower.put("location_area_code", lac);
tower.put("mobile_country_code", mcc);
tower.put("mobile_network_code", mnc);
} catch (JSONException e) {
Log.e(TAG, "call JSONObject's put failed", e);
}

JSONArray array = new JSONArray();
array.put(tower);

List<NeighboringCellInfo> list = mTelMan.getNeighboringCellInfo();
Iterator<NeighboringCellInfo> iter = list.iterator();
NeighboringCellInfo cellInfo;
JSONObject tempTower;
while (iter.hasNext()) {
cellInfo = iter.next();
tempTower = new JSONObject();
try {
tempTower.put("cell_id", cellInfo.getCid());
tempTower.put("location_area_code", cellInfo.getLac());
tempTower.put("mobile_country_code", mcc);
tempTower.put("mobile_network_code", mnc);
} catch (JSONException e) {
Log.e(TAG, "call JSONObject's put failed", e);
}
array.put(tempTower);
}

JSONObject object = createJSONObject("cell_towers", array);
requestLocation(object);
}

private void requestWIFILocation() {
WifiManager wifiMan = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiMan.getConnectionInfo();
String mac = info.getMacAddress();
String ssid = info.getSSID();

JSONObject wifi = new JSONObject();
try {
wifi.put("mac_address", mac);
wifi.put("ssid", ssid);
} catch (JSONException e) {
e.printStackTrace();
}

JSONArray array = new JSONArray();
array.put(wifi);

JSONObject object = createJSONObject("wifi_towers", array);
requestLocation(object);
}

private void requestLocation(JSONObject object) {
Log.d(TAG, "requestLocation: " + object.toString());
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com/loc/json");
try {
StringEntity entity = new StringEntity(object.toString());
post.setEntity(entity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

try {
HttpResponse resp = client.execute(post);
HttpEntity entity = resp.getEntity();
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
StringBuffer buffer = new StringBuffer();
String result = br.readLine();
while (result != null) {
buffer.append(result);
result = br.readLine();
}

Log.d(TAG, buffer.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

private JSONObject createJSONObject(String arrayName, JSONArray array) {
JSONObject object = new JSONObject();
try {
object.put("version", "1.1.0");
object.put("host", "maps.google.com");
object.put(arrayName, array);
} catch (JSONException e) {
Log.e(TAG, "call JSONObject's put failed", e);
}
return object;
}

private void requestGPSLocation() {
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000 * 60, 100, mLocLis);
}

private void requestNetworkLocation() {
LocationManager mLocMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000 * 60, 100, mLocLis);
}

private LocationListener mLocLis = new LocationListener() {

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "onStatusChanged, provider = " + provider);
}

@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "onProviderEnabled, provider = " + provider);
}

@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "onProviderDisabled, provider = " + provider);
}

@Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.d(TAG, "latitude: " + latitude + ", longitude: " + longitude);
}
};
}
本篇文章来源于网络,尚未对其进行实践测试,因为实际应用的关系,这里仅对NetWork方式获取位置做了实践,请稳步 Android使用NetWork方式获取当前的地理位置 一文查看相关内容
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android获取当前位置的三种方式及其使用方法 的相关文章

随机推荐

  • 10种Arduino IDE替代品开始编程

    当我们开始开发Arduino项目时 通常我们倾向于使用Arduino IDE 无论如何 如果我们对标准IDE不满意 我们应该考虑几种Arduino IDE替代方案 众所周知 在开发物联网项目或构建DIY项目时 Arduino是最受欢迎的原型
  • ARM指令集

    ARM指令的基本格式 ARM指令的基本格式为
  • echarts之柱状图(1)

    PS相关学习资料链接 Pink老师的教程分解 O O哈哈 div class bar h2 就业行业 a href 2019 a a href 2020 a h2 div class chart div div css自行设置 类名为cha
  • Failed to execute goal on project rocketmq-console-ng: Could not resolve dependencies for project

    Apache RocketMQ安装部署 Failed to execute goal on project rocketmq console ng Could not resolve dependencies for project org
  • TypeScript(五)类型别名及类型符号

    目录 引言 类型别名 基本用法 字面量类型 数字字面量 字符串字面量 布尔字面量 空字面量 枚举字面量 类型符号 联合类型 交叉类型 类型断言 尖括号 as关键字 非空断言 类型保护 typeof instanceof 类型谓词 索引类型
  • 解决 IProgress not found. Please update jupyter and ipywidgets. 问题

    解决 IProgress not found Please update jupyter and ipywidgets 问题 一 报错 IProgress not found Please update jupyter and ipywid
  • web服务搭建

    Python 吹爆Python 1行代码搭建Web服务器30行代码实现服务器的文件上传下载 需求 手机每日下载图片 然后需经过本人编写的Python脚本处理一遍 再返回到手机上 个人电脑不能保证时刻开机在线 自己也不可能一直在电脑旁边 故欲
  • Firebug 1.9新特性指南

    Firebug 1 9新特性指南 FireBug1 9发布了 引入了很多新特性 一 Firebug兼容的Firefox版本 Firefox4兼容Firebug1 7 3 Firefox5 11兼容Firebug1 9 Firefox12兼容
  • 【Python 协程详解】

    0 前言 前面讲了线程和进程 其实python还有一个特殊的线程就是协程 协程不是计算机提供的 计算机只提供 进程 线程 协程是人工创造的一种用户态切换的微进程 使用一个线程去来回切换多个进程 为什么需要协程 导致Python不能充分利用多
  • 分布式协议与算法——Paxos算法

    目录 Paxos算法 Basic Paxos算法 三种角色 如何达成共识 协商过程 小结 Multi Paxos算法 关于 Multi Paxos 的思考 领导者 优化Basic Paxos Chubby 的 Multi Paxos 实现
  • 解决Elasticsearch查询默认最大值返回10000

    文章目录 1 问题描述 1 描述 2 分析 2 解决方案 1 更改当前索引最大查询条数 max result window 2 能查出数据 但是total依然还是1000 更改track total hits 3 当java使用时应该 4
  • android webview 加载本地html并且解决多图卡顿问题

    使用webview加载本地html 因为本地html使用多张图片 滑动起来卡顿 解决方法如下 把文件夹放入assets文件夹下 Activity加载 WebView wView WebView findViewById R id webvi
  • PANet:基于金字塔注意力网络的图像超分辨率重建(全代码)

    PANet 基于金字塔注意力网络的图像超分辨率重建 本文为全代码 原文请看 传送门 import torch import torch nn as nn import torch nn functional as F from torch
  • 运维实战案例之文件已删除但空间不释放问题解析

    1 错误现象 运维的监控系统发来通知 报告一台服务器空间满了 登陆服务器查看 根分区确实没有空间了 如下图所示 这里首先说明一下服务器的一些删除策略 由于Linux没有回收站功能 我们的线上服务器所有要删除的文件都会首先移动到系统 tmp目
  • 请使用mysql连接池

    在初次使用 python 的 pymysql工具包连接 mysql数据库 的时候 总是发生数据库连接失败的情况发生 经过多方确认 发现这种情况不是自己的连接方式错了 而是mysql数据库服务器因为网络出现闪断 导致在查询的时候发生连接出错的
  • 深度学习与计算机视觉[CS231N] 学习笔记(4.1):反向传播(Backpropagation)

    在学习深度学习的过程中 我们常用的一种优化参数的方法就是梯度下降法 而一般情况下 我们搭建的神经网络的结构是 输入 权重矩阵 损失函数 如下图所示 而在给定输入的情况下 为了使我们的损失函数值达到最小 我们就需要调节权重矩阵 使之满足条件
  • DQN理论基础及其代码实现【Pytorch + CartPole-v0】

    DQN算法的理论基础 基于动态规划方法 基于蒙特卡罗方法和基于时间差分的方法都有一个基本的前提条件 状态空间和动作空间是离散的 而且状态空间和动作空间不能太大 这些强化学习方法的基本步骤是先评估值函数 再利用值函数改善当前的策略 这时的值函
  • ROS rosdep update 出错方法 不需要翻墙切换之类的解决方法 ‘https://raw.githubusercontent.com/ros/rosdistro/master/inde

    系统 ubuntu18 rosdep update参考的这篇文章 https blog csdn net weixin 43311920 article details 114796748 utm source app app versio
  • HBase NoSQL数据库详解

    一 HBase简介 HBase是Hadoop的生态系统 是建立在Hadoop文件系统 HDFS 之上的分布式 面向列的数据库 通过利用Hadoop的文件系统提供容错能力 如果你需要进行实时读写或者随机访问大规模的数据集的时候 请考虑使用HB
  • Android获取当前位置的三种方式及其使用方法

    1 GPS定位 2 基站定位 此类位置的获取有赖于手机无线通讯信号 当手机处在信号覆盖范围内 手机可以获得该区域 即通讯术语中的 小区 的识别号 因为这些识别号是惟一的 因此可以将识别号和地理坐标对应起来 因此根据识别号就可以知道地理位置