google gps定位

1.代码背景 :

Google在2023年五月底 发布现金贷规则不允许使用"ACCESS_FINE_LOCATION",所以我们只能通过"ACCESS_COARSE_LOCATION"来获取定位

2.需要权限


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

3.添加依赖

implementation ("com.google.android.gms:play-services-location:21.2.0")

4.google gps工具类

个人认为定位效果
 1.LocalLocationBySDK  --> 2.LocalLocationByService --> 3.LocalLocationByLast
  

public class GoogleGpsHelper {
    private final static String TAG= "GoogleGpsHelper";
    private static final int REQUEST_RESOLUTION_CODE = 1000;
    private static final long INTERVAL_CONFIG = 10000; //毫秒
    private static final long FAST_INTERVAL_CONFIG = INTERVAL_CONFIG / 2;

    private Activity activity;
    private LocationCallBack locationCallBack;
    private FusedLocationProviderClient mFusedLocationClient;
    private SettingsClient mSettingsClient;
    private LocationRequest mLocationRequest;
    private LocationSettingsRequest mLocationSettingsRequest;
    private LocationCallback mLocationCallback;
    private Location mCurrentLocation;
    private Boolean mRequestingLocationUpdates;

    public GoogleGpsHelper (Activity activity) {
        this.activity= activity;
        init();
    }

    public static GoogleLocation getLocalLocation(Context context) {
        GoogleLocation googleLocation = new GoogleLocation();
       
           
              
          googleLocation=getLocalLocationBySDK()?saveLocalLocationByService()?saveLocalLocationByLast();
          
        return googleLocation;
    }

    public static void saveLocalLocationBySDK(Context context, GoogleLocation googleLocation) {
        SharedPreferences setting_info = context.getSharedPreferences(SDK, MODE_PRIVATE);
        SharedPreferences.Editor edit = setting_info.edit();
        edit.putString("googleLatitude", googleLocation.getGoogleLatitude());
        edit.putString("googleLongitude", googleLocation.getGoogleLongitude());
        edit.commit();
    }
    
     public static void saveLocalLocationByService(Context context, GoogleLocation googleLocation) {
        SharedPreferences setting_info = context.getSharedPreferences(Service, MODE_PRIVATE);
        SharedPreferences.Editor edit = setting_info.edit();
        edit.putString("googleLatitude", googleLocation.getGoogleLatitude());
        edit.putString("googleLongitude", googleLocation.getGoogleLongitude());
        edit.commit();
    }
    
     public static void saveLocalLocationByLast(Context context, GoogleLocation googleLocation) {
        SharedPreferences setting_info = context.getSharedPreferences(Last, MODE_PRIVATE);
        SharedPreferences.Editor edit = setting_info.edit();
        edit.putString("googleLatitude", googleLocation.getGoogleLatitude());
        edit.putString("googleLongitude", googleLocation.getGoogleLongitude());
        edit.commit();
    }

    public static void getSystemLocation(final Context context) {
         new Thread(){
           @Override
           public void run() {
               super.run();
               try {
                   LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                   List<String> providers = locationManager.getProviders(true);
                   Location currentLocation = null;
                   if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                       return;
                   }
                   for (String provider : providers) {
                       Location location = locationManager.getLastKnownLocation(provider);
                       if (location == null) {
                           continue;
                       }
                       if (currentLocation == null || location.getAccuracy() < currentLocation.getAccuracy()) {
                           currentLocation = location;
                       }
                   }
                   if (currentLocation != null) {

                    
                         double lat = location.getLatitude();
                        double lng = location.getLongitude();
                        if (String.valueOf(lng).length() > 6) {
                            GoogleLocation googleLocation = new GoogleLocation();
                            googleLocation.setGoogleLatitude(location.getLatitude() + "");
                            googleLocation.setGoogleLongitude(location.getLongitude() + "");
                            saveLocalLocationByService(context, googleLocation);
                        }
                   }
               }catch (Exception e){
                   e.printStackTrace();
               }
           }
       }.start();

    

    }


    public void setLocationCallBack(LocationCallBack locationCallBack) {
        this.locationCallBack = locationCallBack;
    }

    private void init() {
        mRequestingLocationUpdates = false;
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
        mSettingsClient = LocationServices.getSettingsClient(context);
        createLocationCallback();
        createLocationRequest();
        buildLocationSettingsRequest();
        try {
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(context, new OnSuccessListener<Location>() {

                        @Override
                        public void onSuccess(Location location) {
                            try {
                                if (location != null) {
                                    GoogleLocation googleLocation = new GoogleLocation();
                                    googleLocation.setGoogleLatitude(location.getLatitude() + "");
                                    googleLocation.setGoogleLongitude(location.getLongitude() + "");
                                    saveLocalLocationByLast(context, googleLocation);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void startLocation() {
        startLocationUpdates();
    }

    private void createLocationCallback() {
        mLocationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                super.onLocationResult(locationResult);
                mCurrentLocation = locationResult.getLastLocation();
                stopLocationUpdates();
                GoogleLocation googleLocation = new GoogleLocation();
                googleLocation.setGoogleLatitude(mCurrentLocation.getLatitude() + "");
                googleLocation.setGoogleLongitude(mCurrentLocation.getLongitude() + "");
                saveLocalLocationBySDK(context, googleLocation);
                if (locationCallBack != null) {
                    locationCallBack.onLocationResult(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
                }

            }
        };
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL_CONFIG);
        mLocationRequest.setFastestInterval(FAST_INTERVAL_CONFIG);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
    }

    private void buildLocationSettingsRequest() {
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
        builder.addLocationRequest(mLocationRequest);
        mLocationSettingsRequest = builder.build();
    }

    private void startLocationUpdates() {
        if (!mRequestingLocationUpdates) {
            mRequestingLocationUpdates = true;
        } else {
            return;
        }

        mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
                .addOnSuccessListener(context, new OnSuccessListener<LocationSettingsResponse>() {
                    @SuppressLint("MissingPermission")
                    @Override
                    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            return;
                        }

                        mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                                mLocationCallback, Looper.myLooper());

                    }
                })
                .addOnFailureListener(context, new OnFailureListener() {
                    @Override
                    public void onFailure(@androidx.annotation.NonNull Exception e) {
                        int statusCode = ((ApiException) e).getStatusCode();
                        if (locationCallBack != null) {
                            locationCallBack.onGoogleapisFail("Location fail");
                        }
                        switch (statusCode) {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                try {
                                    // Show the dialog by calling startResolutionForResult(), and check the
                                    // result in onActivityResult().
                                    ResolvableApiException rae = (ResolvableApiException) e;
                                    rae.startResolutionForResult(context, REQUEST_RESOLUTION_CODE);
                                } catch (IntentSender.SendIntentException sie) {
                                }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                                mRequestingLocationUpdates = false;
                        }

                    }
                });
    }

    public void stopLocationUpdates() {
        if (!mRequestingLocationUpdates) {
            return;
        }
        mFusedLocationClient.removeLocationUpdates(mLocationCallback)
                .addOnCompleteListener(context, new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@androidx.annotation.NonNull Task<Void> task) {
                        mRequestingLocationUpdates = false;

                    }
                });
    }

    public abstract static class LocationCallBack {
        public void onLocationResult(double latitude, double longitude) {

        }

        public void onGoogleapisFail(String error) {

        }

        public void onCompleted() {

        }
    }
}


5.使用方法

new对象 调用对应三种定位方法即可

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容