【问题标题】:Android - How to request location update in the new API?Android - 如何在新 API 中请求位置更新?
【发布时间】:2018-11-15 05:17:11
【问题描述】:

我在谷歌的新位置 API 上玩了一下(获取纬度和经度值):

private void getLastLocation(){
    FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    try {
        mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {
                    double latitude = location.getLatitude();
                    double longitude = location.getLongitude();
                    Toast.makeText(getApplicationContext(), String.valueOf(latitude) + "/" + String.valueOf(longitude), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Cannot get location", Toast.LENGTH_LONG).show();
                }
            }
        })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("LocationFetch", "Error trying to get last GPS location");
                        e.printStackTrace();
                    }
                });
    } catch (SecurityException e){
        Log.d("LocationFetch", "Permission missing");
    }
}

当我第一次测试这段代码时,location 总是返回 null。然而,在打开 Instagram(它在我的手机上进行了位置更新 - 地理图标短暂出现)后,location 正在返回我的相关经度和纬度值。

如何使用新 API 在我的应用上请求位置更新,以防止 location 为空或检索非常旧的位置? (getLastLocation()不够,可能LocationRequest?)

值得注意的是,我不希望间隔更新,我希望它在调用一次时在 Android 服务中发生。

【问题讨论】:

标签: java android


【解决方案1】:

这对我有用。基于Official docs,每 10 秒更新一次 Toast 并显示您的位置:

private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;



@Override
protected void onResume() {
    super.onResume();
    startLocationUpdates();

}

private void startLocationUpdates() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    Activity#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for Activity#requestPermissions for more details.
            return;
        }
    }
    fusedLocationClient.requestLocationUpdates(locationRequest,
            locationCallback,
            Looper.getMainLooper());
}

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

private void stopLocationUpdates() {
    fusedLocationClient.removeLocationUpdates(locationCallback);
}

在 onCreate 方法中添加如下代码:

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(2*5000);

    locationCallback=new LocationCallback(){
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null) {
                return;
            }
            for (Location location : locationResult.getLocations()) {
               // if (location != null) {


                    String Lat = String.valueOf(location.getLatitude());
                    String Lon = String.valueOf(location.getLongitude());

                    Toast.makeText(getApplicationContext(), Lat + " - " + Lon, Toast.LENGTH_SHORT).show();
            //    }
            }
        }
    };

【讨论】:

    【解决方案2】:

    首先在你的build.gradle文件中添加这个实现

    implementation 'com.google.android.gms:play-services-location:11.2.0'//include the latest version of play services
    

    在您的活动或片段中实现(实现LocationListener),然后实现其功能,然后

    在您的onCreate() getLocation(); 中调用此方法 然后在这个函数中添加这些行

    protected void getLocation() {
        if (isLocationEnabled(MainActivity.this)) {
            locationManager = (LocationManager)  this.getSystemService(Context.LOCATION_SERVICE);
            criteria = new Criteria();
            bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
    
            //You can still do this if you like, you might get lucky:
            Location location = locationManager.getLastKnownLocation(bestProvider);
            if (location != null) {
                Log.e("TAG", "GPS is on");
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
                searchNearestPlace(voice2text);
            }
            else{
                //This is what you need:
                locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
            }
        }
        else
        {
            //prompt user to enable location....
            //.................
        }
    }
    

    之后在您的onLocationChanged(Location location) 添加这几行代码

    @Override
    public void onLocationChanged(Location location) {
        //Hey, a non null location! Sweet!
    
        //remove location callback:
        locationManager.removeUpdates(this);
    
        //open the map:
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
        searchNearestPlace(voice2text);
    }
    

    你准备好了!!!! 干杯快乐编码

    【讨论】:

      【解决方案3】:

      使用这个类

      public class GPSTracker extends Service implements LocationListener {
      
      private final Context mContext;
      
      // flag for GPS status
      boolean isGPSEnabled = false;
      
      // flag for network status
      boolean isNetworkEnabled = false;
      
      // flag for GPS status
      boolean canGetLocation = false;
      
      Location location; // location
      double latitude; // latitude
      double longitude; // longitude
      
      // The minimum distance to change Updates in meters
      private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
      
      // The minimum time between updates in milliseconds
      private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
      
      // Declaring a Location Manager
      protected LocationManager locationManager;
      
      public GPSTracker(Context context) {
          this.mContext = context;
          getLocation();
      }
      
      @SuppressLint("MissingPermission")
      public Location getLocation() {
          try {
              locationManager = (LocationManager) mContext
                      .getSystemService(LOCATION_SERVICE);
      
              // getting GPS status
              isGPSEnabled = locationManager
                      .isProviderEnabled(LocationManager.GPS_PROVIDER);
      
              // getting network status
              isNetworkEnabled = locationManager
                      .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
      
              if (!isGPSEnabled && !isNetworkEnabled) {
                  // no network provider is enabled
              } else {
                  this.canGetLocation = true;
                  // First get location from Network Provider
                  if (isNetworkEnabled) {
                      locationManager.requestLocationUpdates(
                              LocationManager.NETWORK_PROVIDER,
                              MIN_TIME_BW_UPDATES,
                              MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                      Log.d("Network", "Network");
                      if (locationManager != null) {
                          location = locationManager
                                  .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                          if (location != null) {
                              latitude = location.getLatitude();
                              longitude = location.getLongitude();
                          }
                      }
                  }
                  // if GPS Enabled get lat/long using GPS Services
                  if (isGPSEnabled) {
                      if (location == null) {
                          locationManager.requestLocationUpdates(
                                  LocationManager.GPS_PROVIDER,
                                  MIN_TIME_BW_UPDATES,
                                  MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                          Log.d("GPS Enabled", "GPS Enabled");
                          if (locationManager != null) {
                              location = locationManager
                                      .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                              if (location != null) {
                                  latitude = location.getLatitude();
                                  longitude = location.getLongitude();
                              }
                          }
                      }
                  }
              }
      
          } catch (Exception e) {
              e.printStackTrace();
          }
      
          return location;
      }
      
      /**
       * Stop using GPS listener
       * Calling this function will stop using GPS in your app
       */
      public void stopUsingGPS() {
          if (locationManager != null) {
              locationManager.removeUpdates(GPSTracker.this);
          }
      }
      
      /**
       * Function to get latitude
       */
      public double getLatitude() {
          if (location != null) {
              latitude = location.getLatitude();
          }
      
          // return latitude
          return latitude;
      }
      
      /**
       * Function to get longitude
       */
      public double getLongitude() {
          if (location != null) {
              longitude = location.getLongitude();
          }
      
          // return longitude
          return longitude;
      }
      
      /**
       * Function to check GPS/wifi enabled
       *
       * @return boolean
       */
      public boolean canGetLocation() {
          return this.canGetLocation;
      }
      
      /**
       * Function to show settings alert dialog
       * On pressing Settings button will lauch Settings Options
       */
      public void showSettingsAlert() {
          AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
      
          // Setting Dialog Title
          alertDialog.setTitle("GPS is settings");
      
          // Setting Dialog Message
          alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
      
          // On pressing Settings button
          alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                  mContext.startActivity(intent);
              }
          });
      
          // on pressing cancel button
          alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int which) {
                  dialog.cancel();
              }
          });
      
          // Showing Alert Message
          alertDialog.show();
      }
      
      @Override
      public void onLocationChanged(Location location) {
      }
      
      @Override
      public void onProviderDisabled(String provider) {
      }
      
      @Override
      public void onProviderEnabled(String provider) {
      }
      
      @Override
      public void onStatusChanged(String provider, int status, Bundle extras) {
      }
      
      @Override
      public IBinder onBind(Intent arg0) {
          return null;
      }
      } 
      

      在Ur Activity类中使用这个方法

        double latitude, longitude;
        private void getLocation() {
          GPSTracker gps = new GPSTracker(this);
          if (gps.canGetLocation()) {
      
              latitude = gps.getLatitude();
              longitude = gps.getLongitude();
              Log.d("lat", "" + latitude);
              Log.d("long", "" + longitude);
      
      
          } else {
              // can't get location
              // GPS or Network is not enabled
              // Ask user to enable GPS/network in settings
              gps.showSettingsAlert();
          }
      

      【讨论】:

        【解决方案4】:

        试试这个代码。

        在渐变中

        implementation 'com.google.android.gms:play-services-location:16.0.0'
        

        在代码中

         private void turnGPSOn() {
            LocationRequest mLocationRequest = LocationRequest.create()
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                    .setInterval(10 * 1000)
                    .setFastestInterval(1 * 1000);
        
            LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
                    .addLocationRequest(mLocationRequest);
            settingsBuilder.setAlwaysShow(true);
        
            Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
                    .checkLocationSettings(settingsBuilder.build());
        
            result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
                @Override
                public void onComplete(@NonNull Task<LocationSettingsResponse> task) {
                    try {
                        LocationSettingsResponse response =
                                task.getResult(ApiException.class);
        
                        if (gps.canGetLocation()) {
                            lat = String.valueOf(gps.getLatitude());
                            lon = String.valueOf(gps.getLongitude());
                        }
        
                    } catch (ApiException ex) {
                        switch (ex.getStatusCode()) {
                            case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                try {
                                    ResolvableApiException resolvableApiException =
                                            (ResolvableApiException) ex;
                                    resolvableApiException
                                            .startResolutionForResult(SignupActivity.this,
                                                    REQUEST_CHECK_SETTINGS);
                                } catch (IntentSender.SendIntentException e) {
        
                                }
                                break;
                            case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
        
                                break;
                        }
                    }
                }
            });
        }
        

        【讨论】:

          猜你喜欢
          • 2014-06-03
          • 1970-01-01
          • 2021-12-09
          • 1970-01-01
          • 2016-06-25
          • 1970-01-01
          • 2012-03-06
          • 2015-12-07
          • 2015-05-13
          相关资源
          最近更新 更多