共计 8130 个字符,预计需要花费 21 分钟才能阅读完成。
Android 中应用 GPS 和 NetWork 获取定位信息
在 Android 中定位是属于危险权限,须要在增加 Mainfest.xml 中增加。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
如果在 Android6.0 级以上零碎,须要 动静的申请权限,也能够应用封装好 权限治理库。
定位的几种形式
在 Android 零碎当中,给咱们提供了四种定位形式,别离是:
network
它是依附信号塔或 WiFi 来定位的。对应的 provider 字段是 LocationManager.NETWORK_PROVIDER,是一种低精度,低耗电的初略定位形式。
gps
它是依附 GPS 来定位的。对应的 provider 字段是 LocationManager.GPS_PROVIDER,是高精度,高耗电的精准定位形式。
passive
被动的获取定位信息,通过承受其余 APP 或 service 的定位信息。不过须要这个权限 ACCESS_FINE_LOCATION。
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
fused
Google 曾经将这个定位形式 hide 了。
获取定位的 api 封装
public class LocationUtils {
private static final long REFRESH_TIME = 5000L;
private static final float METER_POSITION = 0.0f;
private static ILocationListener mLocationListener;
private static LocationListener listener = new MyLocationListener();
private static class MyLocationListener implements LocationListener {
@Override
public void onLocationChanged(Location location) {// 定位扭转监听
if (mLocationListener != null) {mLocationListener.onSuccessLocation(location);
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {// 定位状态监听}
@Override
public void onProviderEnabled(String provider) {// 定位状态可用监听}
@Override
public void onProviderDisabled(String provider) {// 定位状态不可用监听}
}
/**
* GPS 获取定位形式
*/
public static Location getGPSLocation(@NonNull Context context) {
Location location = null;
LocationManager manager = getLocationManager(context);
// 高版本的权限查看
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return null;}
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {// 是否反对 GPS 定位
// 获取最初的 GPS 定位信息,如果是第一次关上,个别会拿不到定位信息,个别能够申请监听,在无效的工夫范畴能够获取定位信息
location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
return location;
}
/**
* network 获取定位形式
*/
public static Location getNetWorkLocation(Context context) {
Location location = null;
LocationManager manager = getLocationManager(context);
// 高版本的权限查看
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return null;}
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {// 是否反对 Network 定位
// 获取最初的 network 定位信息
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
return location;
}
/**
* 获取最好的定位形式
*/
public static Location getBestLocation(Context context, Criteria criteria) {
Location location;
LocationManager manager = getLocationManager(context);
if (criteria == null) {criteria = new Criteria();
}
String provider = manager.getBestProvider(criteria, true);
if (TextUtils.isEmpty(provider)) {
// 如果找不到最适宜的定位,应用 network 定位
location = getNetWorkLocation(context);
} else {
// 高版本的权限查看
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return null;}
// 获取最适宜的定位形式的最初的定位权限
location = manager.getLastKnownLocation(provider);
}
return location;
}
/**
* 定位监听
*/
public static void addLocationListener(Context context, String provider, ILocationListener locationListener) {addLocationListener(context, provider, REFRESH_TIME, METER_POSITION, locationListener);
}
/**
* 定位监听
*/
public static void addLocationListener(Context context, String provider, long time, float meter, ILocationListener locationListener) {if (locationListener != null) {mLocationListener = locationListener;}
if (listener == null) {listener = new MyLocationListener();
}
LocationManager manager = getLocationManager(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}
manager.requestLocationUpdates(provider, time, meter, listener);
}
/**
* 勾销定位监听
*/
public static void unRegisterListener(Context context) {if (listener != null) {LocationManager manager = getLocationManager(context);
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {return;}
// 移除定位监听
manager.removeUpdates(listener);
}
}
private static LocationManager getLocationManager(@NonNull Context context) {return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
/**
* 自定义接口
*/
public interface ILocationListener {void onSuccessLocation(Location location);
}
}
获取定位应用实例
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private boolean flag;
private Button gsp_btn;
private Button network_btn;
private Button best_btn;
private static Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
initView();
initListener();}
private void initListener() {gsp_btn.setOnClickListener(this);
network_btn.setOnClickListener(this);
best_btn.setOnClickListener(this);
}
@Override
protected void onResume() {super.onResume();
initPermission();// 针对 6.0 以上版本做权限适配}
private void initView() {gsp_btn = (Button) findViewById(R.id.gps);
network_btn = (Button) findViewById(R.id.net);
best_btn = (Button) findViewById(R.id.best);
}
private void initPermission() {if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 查看权限
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
|| ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// 申请权限
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {flag = true;}
} else {flag = true;}
}
/**
* 权限的后果回调函数
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {flag = grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED;
}
}
@Override
public void onClick(View v) {switch (v.getId()) {
case R.id.gps:
if (flag) {getGPSLocation();
} else {Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();}
break;
case R.id.net:
if (flag) {getNetworkLocation();
} else {Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();}
break;
case R.id.best:
if (flag) {getBestLocation();
} else {Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();}
break;
}
}
/**
* 通过 GPS 获取定位信息
*/
public void getGPSLocation() {Location gps = LocationUtils.getGPSLocation(this);
if (gps == null) {
// 设置定位监听,因为 GPS 定位,第一次进来可能获取不到,通过设置监听,能够在无效的工夫范畴内获取定位信息
LocationUtils.addLocationListener(context, LocationManager.GPS_PROVIDER, new LocationUtils.ILocationListener() {
@Override
public void onSuccessLocation(Location location) {if (location != null) {Toast.makeText(MainActivity.this, "gps onSuccessLocation location: lat==" + location.getLatitude() + "lng==" + location.getLongitude(), Toast.LENGTH_SHORT).show();} else {Toast.makeText(MainActivity.this, "gps location is null", Toast.LENGTH_SHORT).show();}
}
});
} else {Toast.makeText(this, "gps location: lat==" + gps.getLatitude() + "lng==" + gps.getLongitude(), Toast.LENGTH_SHORT).show();}
}
/**
* 通过网络等获取定位信息
*/
private void getNetworkLocation() {Location net = LocationUtils.getNetWorkLocation(this);
if (net == null) {Toast.makeText(this, "net location is null", Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, "network location: lat==" + net.getLatitude() + "lng==" + net.getLongitude(), Toast.LENGTH_SHORT).show();}
}
/**
* 采纳最好的形式获取定位信息
*/
private void getBestLocation() {Criteria c = new Criteria();//Criteria 类是设置定位的规范信息(零碎会依据你的要求,匹配最适宜你的定位供应商),一个定位的辅助信息的类
c.setPowerRequirement(Criteria.POWER_LOW);// 设置低耗电
c.setAltitudeRequired(true);// 设置须要海拔
c.setBearingAccuracy(Criteria.ACCURACY_COARSE);// 设置 COARSE 精度规范
c.setAccuracy(Criteria.ACCURACY_LOW);// 设置低精度
//... Criteria 还有其余属性,就不一一介绍了
Location best = LocationUtils.getBestLocation(this, c);
if (best == null) {Toast.makeText(this, "best location is null", Toast.LENGTH_SHORT).show();} else {Toast.makeText(this, "best location: lat==" + best.getLatitude() + "lng==" + best.getLongitude(), Toast.LENGTH_SHORT).show();}
}
}
对于 GPS 定位的信息还有比拟多的内容,在 API24 中 GpsStauts 类过期,应用 GnssStatus 类替换,同时在 LocationManager 中的一些 GPS 状态的监听,也被新的 API 退换。
正文完