Android开发中使用GPS和NetWork获取定位信息
程序员文章站
2022-09-28 12:12:45
Android开发中使用GPS和NetWork获取定位信息。在Android中定位是属于危险权限,需要在添加Mainfest.xml中添加。
如果在Android6....
Android开发中使用GPS和NetWork获取定位信息。在Android中定位是属于危险权限,需要在添加Mainfest.xml中添加。
如果在Android6.0级以上系统,需要动态的申请权限,也可以使用封装好权限管理库。
定位的几种方式
在Android系统当中,给我们提供了四种定位方式,分别是:
-
network
它是依靠信号塔或WiFi来定位的。对应的provider字段是LocationManager.NETWORK_PROVIDER,是一种低精度,低耗电的初略定位方式。
-
gps
它是依靠GPS来定位的。对应的provider字段是LocationManager.GPS_PROVIDER,是高精度,高耗电的精准定位方式。
-
passive
被动的获取定位信息,通过接受其他APP或service的定位信息。不过需要这个权限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退换。