xml文件,在此实现demo未使用到三个textView,需要自己在下面的MainActivity文件修改一下代码 此实现的是使用LocationManager.FUSED_PROVIDER融合定位实现高精度获取经纬度的代码,是在
https://blog.csdn.net/yuran06/article/details/123802511?spm=1001.2014.3001.5506
代码上进行修改,特此感谢
代码两种实现情况,删除MainActivity以下代码:
mLocationInfo = location.toString();
mHandler.sendEmptyMessage(MSG_REFRESH_UI);
Log.d("MainActivity", "onLocationChanged: location " + location.toString());
Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
if(msg.what == MSG_REFRESH_UI){
refreshUI();
}
return false;
}
});
private void refreshUI(){
lat.setText("Location:" + mLocationInfo);
}
即可以实现普通精度获取经纬度,位置demo 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"
tools:context=".MainActivity">
<Button
android:id="@+id/bt_location"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click to get position"
android:gravity="center_horizontal"
tools:ignore="MissingConstraints" />
<TextView
android:id="@+id/tv_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textColor="@color/black"
app:layout_constraintBottom_toTopOf="@+id/tv_longitude"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="经度"
android:textColor="@color/black"
app:layout_constraintBottom_toTopOf="@+id/tv_nowAddress"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
android:visibility="gone"
app:layout_constraintTop_toBottomOf="@id/tv_latitude" />
<TextView
android:id="@+id/tv_nowAddress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="当前位置"
android:visibility="gone"
android:textColor="@color/black"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity类:
package com.example.getlocation;
import static android.location.LocationRequest.PASSIVE_INTERVAL;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.util.Preconditions;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationRequest;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.location.LocationServices;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
public class MainActivity extends AppCompatActivity implements LocationListener {
private Button bt;
// 定义TextView
private TextView nowAddress;
private TextView lat;
private TextView lon;
// 定义双精度类型的经纬度
private Double longitude,latitude;
// 定义位置管理器
private LocationManager locationManager;
private String mLocationInfo;
private static final int MSG_REFRESH_UI = 1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 得到对应视图ID
nowAddress = findViewById(R.id.tv_nowAddress);
lat = findViewById(R.id.tv_latitude);
lon = findViewById(R.id.tv_longitude);
bt=findViewById(R.id.bt_location);
// 判断当前是否拥有使用GPS的权限
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
// 申请权限
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION}, 100);
}
bt.setOnClickListener(new View.OnClickListener(){
@RequiresApi(api = Build.VERSION_CODES.S)
@Override
public void onClick(View v) {
getLocation();
Log.d("MainActivity","你点击了");
}
});
// getLocation();
/*
或者这样子也是可以的
// 获取当前位置管理器
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 启动位置请求
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, MainActivity.this);
*/
}
private static final long LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS = 1000;
private static final Executor DIRECT_EXECUTOR = Runnable::run;
@RequiresApi(api = Build.VERSION_CODES.S)
@SuppressLint("MissingPermission")
private void getLocation() {
// 获取当前位置管理器
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 启动位置请求
// LocationManager.GPS_PROVIDER GPS定位
// LocationManager.NETWORK_PROVIDER 网络定位
// LocationManager.PASSIVE_PROVIDER 被动接受定位信息
LocationRequest.Builder locationRequest = new LocationRequest.Builder(LOCATION_UPDATE_MIN_TIME_INTERVAL_MILLIS).setMaxUpdates(1);
locationRequest.setQuality(LocationRequest.QUALITY_HIGH_ACCURACY);
locationRequest.build();
//requestLocationUpdates()第一个参数是String Provider;第二个参数是位置更新时间(以毫秒为单位);第三个参数是位置更新的最小距离间隔(以米为单位)
locationManager.requestLocationUpdates(LocationManager.FUSED_PROVIDER, locationRequest.build(),DIRECT_EXECUTOR, MainActivity.this);
}
// 当位置改变时执行,除了移动设置距离为 0时
@Override
public void onLocationChanged(@NonNull Location location) {
mLocationInfo = location.toString();
mHandler.sendEmptyMessage(MSG_REFRESH_UI);
Log.d("MainActivity", "onLocationChanged: location " + location.toString());
// 获取当前纬度
/*latitude = location.getLatitude();
// 获取当前经度
longitude = location.getLongitude();
lat.setText("Latitude:" + latitude);
lon.setText("Longitude:" + longitude);
// 定义位置解析
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
try {
// 获取经纬度对于的位置
// getFromLocation(纬度, 经度, 最多获取的位置数量)
List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 2);
// 得到第一个经纬度位置解析信息
Address address = addresses.get(0);
// 获取到详细的当前位置
// Address里面还有很多方法你们可以自行实现去尝试。比如具体省的名称、市的名称...
String info = address.getAddressLine(0) + // 获取国家名称
address.getAddressLine(1) + // 获取省市县(区)
address.getAddressLine(2); // 获取镇号(地址名称)
// 赋值
nowAddress.setText(info);
} catch (IOException e) {
e.printStackTrace();
}
// 移除位置管理器
// 需要一直获取位置信息可以去掉这个
//locationManager.removeUpdates(this); */
locationManager.removeUpdates(this);
}
Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(@NonNull Message msg) {
if(msg.what == MSG_REFRESH_UI){
refreshUI();
}
return false;
}
});
private void refreshUI(){
lat.setText("Location:" + mLocationInfo);
}
// 当前定位提供者状态
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e("onStatusChanged", provider);
}
// 任意定位提高者启动执行
@Override
public void onProviderEnabled(@NonNull String provider) {
Log.e("onProviderEnabled", provider);
}
// 任意定位提高者关闭执行
@Override
public void onProviderDisabled(@NonNull String provider) {
Log.e("onProviderDisabled", provider);
}
}
申请权限androidmanifest.xml文件
<!-- 网络权限 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 用于进行网络定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 用于获取wifi的获取权限,wifi信息会用来进行网络定位 -->
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
版权声明:本文为qq_43722933原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。