等待设备获取位置数据

时间:2018-08-09 10:06:34

标签: java android

在我的应用中,我从用户那里获取GPS坐标。刚刚激活GPS后,即使在获取坐标之前,我的应用程序仍会继续运行,因此该位置为空。 我注意到onLocationChanged方法确实可以实现并且可能是它的关键,但是如何确保主类中的代码不会获取空值并等待直到位置不为null为止?

主要代码:

if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
  requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
   } else {
    progressBar.setVisibility(View.VISIBLE);
    GPSFetch t = new GPSFetch(getActivity().getApplicationContext());
    Location location = t.getLocation();

    if (location == null) {
       //Toast
    } else {
        lat = location.getLatitude();
        lon = location.getLongitude();
    }
    new GetContacts().execute();
}

GPSFetch:

public Location getLocation(){
    if (ContextCompat.checkSelfPermission( context, android.Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED) 
{
        return null;
    }
    try {
        LocationManager lm = (LocationManager) context.getSystemService(LOCATION_SERVICE);
        boolean isGPSEnabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (isGPSEnabled){
            lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,this);
            Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            return loc;
        }else{

        }
    }catch (Exception e){
        e.printStackTrace();
    }
    return null;
}


@Override
public void onLocationChanged(Location location) {
      Log.d("4", "changed");
}

2 个答案:

答案 0 :(得分:0)

该方法称为onLocationChanged。这意味着有一个价值。

注意:您实际上是从android设备的本地播放服务api获取GPS坐标。详细了解位置服务here

答案 1 :(得分:0)

First you check your gps is on or not, if gps is on then onlocation changed method give lat and lon.



you can check using following code



  public static boolean checkGps(Activity mContext) {

        LocationManager service = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
        boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);

        return enabled;

    }




its return true then gps on otherwise not




if gps not on then on gps programatically using this code



    public void displayLocationSettingsRequest() {
        GoogleApiClient googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API).build();
        googleApiClient.connect();

        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(10000);
        locationRequest.setFastestInterval(10000 / 2);

        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);

        PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
        result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
            @Override
            public void onResult(LocationSettingsResult result) {
                final Status status = result.getStatus();
                switch (status.getStatusCode()) {
                    case LocationSettingsStatusCodes.SUCCESS:
                        Log.e("LocationSetting.SUCCESS", "All location settings are satisfied.");
//                        openMap();
                        break;
                    case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                        Log.e("LocationSetting.SUCCESS", "Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                        try {
                            // Show the dialog by calling startResolutionForResult(), and check the result
                            // in onActivityResult().
                            status.startResolutionForResult(HomeActivity.this, REQUEST_CHECK_SETTINGS);
                        } catch (IntentSender.SendIntentException e) {
                            Log.e("LocationSetting.SUCCESS", "PendingIntent unable to execute request.");
                        }
                        break;
                    case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                        Log.e("LocationSetting.SUCCESS", "Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                        break;
                }
            }
        });
    }



this ask you about gps on or cancel if you press ok then you can fetch result of its in onactivityresult method



like this



  @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == 100) {
            if (resultCode == Activity.RESULT_OK) {
                String result = data.getStringExtra("result");
                Log.e("RESULT_OK", result + "");


              // now your gps is on you can handle your location code here
            }
            if (resultCode == Activity.RESULT_CANCELED) {
                Utils.showToastPopup(this, "Please Turn On Gps");

                // show custom popup when user denied this gps permission and check again 
                when click button or on resume 
            }
        }
}



and then fetch your lat lon inside onlocationchanged



 @Override
    public void onLocationChanged(Location location) {


        latitude = location.getLatitude();
        longitude = location.getLongitude();

}