本文介绍了Android通过原生APi获取所在位置的经纬度。
场景:新增一个功能,用户app主页后,将用户的经纬度通过一个接口返回给服务端,从而让服务器可以准确定位。
步骤分析:
权限问题 :
Android 6.0之后新增动态权限,而获取获取经纬度坐标的权限如果你的app的(TargetVersion>=23)就需要动态获取了(当然也得在清单文件中设置)
代码实现(具体请看下文)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class MainActivity extends AppCompatActivity {
private static final int LOCATION_CODE = 1;
private LocationManager lm;//位置管理
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// 定位权限申请
GPSQunaxian();
}
/**
* 定位权限申请
*/
public void GPSQunaxian(){
lm = (LocationManager) MainActivity.this.getSystemService(MainActivity.this.LOCATION_SERVICE);
boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (ok) {//开了定位服务
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("kly","没有权限");
// 没有权限,申请权限。
// 申请授权。
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
//Toast.makeText(getActivity(), "没有权限", Toast.LENGTH_SHORT).show();
} else {
// 有权限了,去放肆吧。
//Toast.makeText(getActivity(), "有权限", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("kly","d系统检测到未开启GPS定位服务");
Toast.makeText(MainActivity.this, "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 1315);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被用户同意。
} else {
// 权限被用户拒绝了。
Toast.makeText(MainActivity.this, "定位权限被禁止,相关地图功能无法使用!",Toast.LENGTH_LONG).show();
}
}
}
}
}
package com.gentek.tianlin12.utils;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import java.util.List;
/**
* Created by Administrator on 2018/4/17.
* 获取用户的地理位置
*/
public class GPSUtils {
private static GPSUtils instance;
private LocationManager locationManager;
private String locationProvider;
private Location location;
private Context mContext;
private GPSUtils(Context context) {
this.mContext = context;
getLocation();
}
public static GPSUtils getInstance(Context context) {
if (instance == null) {
synchronized (GPSUtils.class) {
if (instance == null) {
instance = new GPSUtils(context);
}
}
}
return instance;
}
private void getLocation() {
//1.获取位置管理器
locationManager = (LocationManager) mContext.getSystemService( Context.LOCATION_SERVICE );
//2.获取位置提供器,GPS或是NetWork
List<String> providers = locationManager.getProviders( true );
if (providers.contains( LocationManager.NETWORK_PROVIDER )) {
//如果是网络定位
Log.d( "kly", "如果是网络定位" );
locationProvider = LocationManager.NETWORK_PROVIDER;
} else if (providers.contains( LocationManager.GPS_PROVIDER )) {
//如果是GPS定位
Log.d( "kly", "如果是GPS定位" );
locationProvider = LocationManager.GPS_PROVIDER;
} else {
Log.d( "kly", "没有可用的位置提供器" );
return;
}
// 需要检查权限,否则编译报错,想抽取成方法都不行,还是会报错。只能这样重复 code 了。
if (Build.VERSION.SDK_INT >= 23 &&
ActivityCompat.checkSelfPermission( mContext, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission( mContext, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
return;
}
//3.获取上次的位置,一般第一次运行,此值为null
Location location = locationManager.getLastKnownLocation( locationProvider );
if (location != null) {
setLocation( location );
}else {
Log.d("kly","location=null");
}
// 监视地理位置变化,第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
locationManager.requestLocationUpdates( locationProvider, 0, 0, locationListener );
}
private void setLocation(Location location) {
this.location = location;
String address = "纬度:" + location.getLatitude() + "经度:" + location.getLongitude();
Log.d( "kly", "address"+address );
}
//获取经纬度
public Location showLocation() {
return location;
}
// 移除定位监听
public void removeLocationUpdatesListener() {
// 需要检查权限,否则编译不过
if (Build.VERSION.SDK_INT >= 23 &&
ActivityCompat.checkSelfPermission( mContext, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission( mContext, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (locationManager != null) {
instance = null;
locationManager.removeUpdates( locationListener );
}
}
/**
* LocationListern监听器
* 参数:地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
*/
LocationListener locationListener = new LocationListener() {
/**
* 当某个位置提供者的状态发生改变时
*/
@Override
public void onStatusChanged(String provider, int status, Bundle arg2) {
}
/**
* 某个设备打开时
*/
@Override
public void onProviderEnabled(String provider) {
}
/**
* 某个设备关闭时
*/
@Override
public void onProviderDisabled(String provider) {
}
/**
* 手机位置发生变动
*/
@Override
public void onLocationChanged(Location location) {
location.getAccuracy();//精确度
setLocation(location);
}
};
}
public class MainActivity extends AppCompatActivity {
private static final int LOCATION_CODE = 1;
private LocationManager lm;//位置管理
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_main );
// 定位权限申请
GPSQunaxian();
Location location = GPSUtils.getInstance( MainActivity.this ).showLocation();
if (location != null) {
String address = "纬度:" + location.getLatitude() + "经度:" + location.getLongitude();
Log.d( "kly",address );
Toast.makeText(MyApplication.getContext(),address,Toast.LENGTH_SHORT).show();
}
}
/**
* 定位权限申请
*/
public void GPSQunaxian(){
lm = (LocationManager) MainActivity.this.getSystemService(MainActivity.this.LOCATION_SERVICE);
boolean ok = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (ok) {//开了定位服务
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
Log.d("kly","没有权限");
// 没有权限,申请权限。
// 申请授权。
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, LOCATION_CODE);
//Toast.makeText(getActivity(), "没有权限", Toast.LENGTH_SHORT).show();
} else {
// 有权限了,去放肆吧。
//Toast.makeText(getActivity(), "有权限", Toast.LENGTH_SHORT).show();
}
} else {
Log.d("kly","d系统检测到未开启GPS定位服务");
Toast.makeText(MainActivity.this, "系统检测到未开启GPS定位服务", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 1315);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_CODE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限被用户同意。
} else {
// 权限被用户拒绝了。
Toast.makeText(MainActivity.this, "定位权限被禁止,相关地图功能无法使用!",Toast.LENGTH_LONG).show();
}
}
}
}
@Override
protected void onDestroy() {
super.onDestroy();
GPSUtils.getInstance( this ).removeLocationUpdatesListener();
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助