基于Android 10.0平台
1.概述
Android系统中的定位服务为LocationManager ,我们无需引入第三方服务,就可以很方便的实现定位逻辑。这篇文章主要为大家介绍了Android原生定位服务LocationManager实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助。
实例功能简单:通过LocationManager获取设备的经纬度,并将其转换成具体的地址,做一个简单的显示功能。
2.实现步骤
2.1 动态申请定位权限
在Android中,可以使用checkSelfPermission()方法来检查应用是否已经被授权了某个权限。对于定位权限,你需要检查ACCESS_COARSE_LOCATION和ACCESS_FINE_LOCATION两个权限。
(1)AndroidManifest.xml声明权限
// 定位权限,需要动态申请
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
// 网络权限,静态申请
<uses-permission android:name="android.permission.INTERNET" />
(2)检查并动态申请定位权限
public void requestPermission() {
// (1)检查应用是否已经授权定位权限
boolean permissionsCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED;;
if (!permissionsCheck) {
Log.d(TAG, "应用未获取权限,请求获取定位权限");
// (2)没有授权定位权限的情况下,申请权限
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
Log.d(TAG, "应用已经被授权定位权限,可以进行定位操作");
}
}
(3)处理权限申请结果
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION: {
Log.d(TAG,"REQUEST_LOCATION_PERMISSION");
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// 定位权限申请成功,进入步骤四:开始使用定位功能
Log.d(TAG, "定位权限申请成功");
Toast.makeText(this, "定位权限申请成功", Toast.LENGTH_SHORT).show();
} else {
// 定位权限申请失败,可以显示一个提示信息给用户
Toast.makeText(this, "定位权限申请失败", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
2.2 使用定位功能
一般获取位置有两种方式NetWork与GPS,这里让系统自动提供最好的方式,当设备在室内的时候就会以网络的定位提供,当设备在室外的时候就可以提供GPS定位。
private void createNativeLocation() {
Log.d(TAG,"createNativeLocation()");
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new MyLocationListener();
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);//不要求海拔
criteria.setBearingRequired(false);//不要求方位
criteria.setCostAllowed(true);//允许有花费
criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
String provider = mLocationManager.getBestProvider(criteria, true); // 提供最好的方式
Log.d(TAG,"定位的provider:" + provider);
mTextProvider.setText("Provider: " + provider);
Location location = mLocationManager.getLastKnownLocation(provider);
Log.d(TAG,"location-" + location);
if (location != null) {
//不为空,显示地理位置经纬度
String longitude = "Longitude:" + location.getLongitude();
String latitude = "Latitude:" + location.getLatitude();
Log.d(TAG,"getLastKnownLocation:" + longitude + "-" + latitude);
}
//第二个参数是间隔时间 第三个参数是间隔多少距离,这里我试过了不同的各种组合,能获取到位置就是能,不能获取就是不能
mLocationManager.requestLocationUpdates(provider, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListener);
}
2.3 监听位置改变
状态和位置信息改变时,可以及时更新信息。在requestLocationUpdates()方法是设置进去。
class MyLocationListener implements LocationListener {
// 位置改变时获取经纬度
@Override
public void onLocationChanged(Location location) {
String longitude = "经度: " + location.getLongitude();
String latitude = "纬度: " + location.getLatitude();
Log.d(TAG,"onLocationChanged:" + longitude + "-" + latitude);
mTextXY.setText(longitude + " - " + latitude);
// 根据当前经纬度查询地址
String locationAddress = getAddressFromLocation(location.getLatitude(), location.getLongitude(), MainActivity.this);
mTextAddress.setText("地址: " + locationAddress);
Log.d(TAG,"地址: " + locationAddress);
}
// 状态改变时
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG,"onStatusChanged - provider:"+provider +" status:"+status);
}
// 提供者可以使用时
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG,"GPS开启了");
}
// 提供者不可以使用时
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG,"GPS关闭了");
}
}
2.4 根据当前经纬度查询地址
在LocationListener中获取到经纬度后,可以根据经纬度去查询地址信息。
public static String getAddressFromLocation(double latitude, double longitude, Context context) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && !addresses.isEmpty()) {
Address address = addresses.get(0);
// 可以从Address对象中获取更多的地址信息
return address.getAddressLine(0);
}
} catch (IOException ioException) {
// 网络问题或I/O错误
}
return null;
}
以上代码中,我们创建了一个Geocoder对象,并通过getFromLocation方法来获取指定经纬度的地址信息,然后通过getAddressLine方法获取到地址信息。
3.完整代码
3.1 activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00000000"
tools:context=".MainActivity">
<TextView
android:id="@+id/text_provider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="10dp"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:textSize="16sp"
android:text="provider暂未获取数据">
</TextView>
<TextView
android:id="@+id/text_xy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
app:layout_constraintTop_toBottomOf="@id/text_provider"
app:layout_constraintLeft_toLeftOf="parent"
android:textSize="16sp"
android:text="经纬度暂未获取数据">
</TextView>
<TextView
android:id="@+id/text_address"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
app:layout_constraintTop_toBottomOf="@id/text_xy"
app:layout_constraintLeft_toLeftOf="parent"
android:textSize="16sp"
android:text="地址暂未获取数据">
</TextView>
</androidx.constraintlayout.widget.ConstraintLayout>
3.2 AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.GPSTest"
tools:targetApi="31">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
3.3 MainActivity.java
package com.zhiyi.gpstest;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "GPSTest";
private static final int REQUEST_LOCATION_PERMISSION = 100;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 0f;
private LocationManager mLocationManager;
private LocationListener mLocationListener;
private TextView mTextProvider;
private TextView mTextXY;
private TextView mTextAddress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG,"onCreate()");
setContentView(R.layout.activity_main);
mTextProvider = (TextView) findViewById(R.id.text_provider);
mTextXY = (TextView) findViewById(R.id.text_xy);
mTextAddress = (TextView) findViewById(R.id.text_address);
// 申请权限
requestPermission();
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG,"onResume()");
try {
createNativeLocation();
} catch (SecurityException e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
if (mLocationManager == null || mLocationListener == null) {
return;
}
mLocationManager.removeUpdates(mLocationListener);
}
// 原生的定位服务
private void createNativeLocation() {
Log.d(TAG,"createNativeLocation()");
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new MyLocationListener();
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);//不要求海拔
criteria.setBearingRequired(false);//不要求方位
criteria.setCostAllowed(true);//允许有花费
criteria.setPowerRequirement(Criteria.POWER_LOW);//低功耗
String provider = mLocationManager.getBestProvider(criteria, true);
Log.d(TAG,"定位的provider:" + provider);
mTextProvider.setText("Provider: " + provider);
Location location = mLocationManager.getLastKnownLocation(provider);
Log.d(TAG,"location-" + location);
if (location != null) {
//不为空,显示地理位置经纬度
String longitude = "Longitude:" + location.getLongitude();
String latitude = "Latitude:" + location.getLatitude();
Log.d(TAG,"getLastKnownLocation:" + longitude + "-" + latitude);
}
//第二个参数是间隔时间 第三个参数是间隔多少距离,这里我试过了不同的各种组合,能获取到位置就是能,不能获取就是不能
mLocationManager.requestLocationUpdates(provider, LOCATION_INTERVAL, LOCATION_DISTANCE, mLocationListener);
}
class MyLocationListener implements LocationListener {
// 位置改变时获取经纬度
@Override
public void onLocationChanged(Location location) {
String longitude = "经度: " + location.getLongitude();
String latitude = "纬度: " + location.getLatitude();
Log.d(TAG,"onLocationChanged:" + longitude + "-" + latitude);
mTextXY.setText(longitude + " - " + latitude);
String locationAddress = getAddressFromLocation(location.getLatitude(), location.getLongitude(), MainActivity.this);
mTextAddress.setText("地址: " + locationAddress);
Log.d(TAG,"地址: " + locationAddress);
}
// 状态改变时
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG,"onStatusChanged - provider:"+provider +" status:"+status);
}
// 提供者可以使用时
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG,"GPS开启了");
}
// 提供者不可以使用时
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG,"GPS关闭了");
}
}
public static String getAddressFromLocation(double latitude, double longitude, Context context) {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
List<Address> addresses;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
if (addresses != null && !addresses.isEmpty()) {
Address address = addresses.get(0);
// 可以从Address对象中获取更多的地址信息
return address.getAddressLine(0);
}
} catch (IOException ioException) {
// 网络问题或I/O错误
}
return null;
}
public void requestPermission() {
boolean permissionsCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
== PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED;;
if (!permissionsCheck) {
Log.d(TAG, "应用未获取权限,请求获取定位权限");
ActivityCompat.requestPermissions(this,
new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
Log.d(TAG, "应用已经被授权定位权限,可以进行定位操作");
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],
int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION: {
Log.d(TAG,"REQUEST_LOCATION_PERMISSION");
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
// 定位权限申请成功,进入步骤四:开始使用定位功能
Log.d(TAG, "定位权限申请成功");
Toast.makeText(this, "定位权限申请成功", Toast.LENGTH_SHORT).show();
} else {
// 定位权限申请失败,可以显示一个提示信息给用户
Toast.makeText(this, "定位权限申请失败", Toast.LENGTH_SHORT).show();
}
break;
}
}
}
}