使用位置对话框获取用户的最后一个已知位置

时间:2018-11-29 18:16:20

标签: android

我正在尝试在用户单击“启用位置”对话框上的“确定”后获取用户的最后一个已知位置。请让我知道应该在哪里实现获取最后一个已知位置的功能。

下面是我的代码:

public class BrodReceiver extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks,
     GoogleApiClient.OnConnectionFailedListener,LocationListener{

LinearLayout linear;
GoogleApiClient mGoogleApiClient;
private static final String BROADCAST_ACTION = "android.location.PROVIDERS_CHANGED";
private static final int ACCESS_FINE_LOCATION_INTENT_ID = 3;
private static final int REQUEST_CHECK_SETTINGS = 0x1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_brod_receiver);

    linear = findViewById(R.id.linear);

    mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    checkPermissions();
  }

 @Override
protected void onStop() {
    super.onStop();

    if(mGoogleApiClient.isConnected()){

        mGoogleApiClient.disconnect();
    }
  }

 @Override
public void onConnected(@Nullable Bundle bundle) {

}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onLocationChanged(Location location) {

}

private void checkPermissions(){

    if (Build.VERSION.SDK_INT >= 23) {
        if (ContextCompat.checkSelfPermission(BrodReceiver.this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED)
            requestLocationPermission();
        else
            showSettingDialog();
    } else
        showSettingDialog();
}

 private void requestLocationPermission() {

    if (ActivityCompat.shouldShowRequestPermissionRationale(BrodReceiver.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
        ActivityCompat.requestPermissions(BrodReceiver.this,
                new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
                ACCESS_FINE_LOCATION_INTENT_ID);

    } else {
        ActivityCompat.requestPermissions(BrodReceiver.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                ACCESS_FINE_LOCATION_INTENT_ID);
     }
   }

  private void showSettingDialog(){

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(30 * 1000);
    locationRequest.setFastestInterval(5 * 1000);//5 sec Time interval for location update
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result =
            LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

        @Override
        public void onResult(@NonNull LocationSettingsResult locationSettingsResult) {

            final Status status = locationSettingsResult.getStatus();
            final LocationSettingsStates state = locationSettingsResult.getLocationSettingsStates();

            switch (status.getStatusCode()) {

                case LocationSettingsStatusCodes.SUCCESS:

                    Toast.makeText(getApplicationContext(),"GPS activated",Toast.LENGTH_SHORT).show();
                    break;

                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:

                    try {
                        status.startResolutionForResult(BrodReceiver.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        e.printStackTrace();
                    }
                    break;

                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:

                    break;
            }
        }
    });
  }


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

      switch(requestCode){

          case REQUEST_CHECK_SETTINGS:

              switch(resultCode){

                  case RESULT_OK:
                      Log.e("Settings", "Result OK");

                      Toast.makeText(getApplicationContext(),"GPS enabled",Toast.LENGTH_SHORT).show();
                      //startLocationUpdates();
                      break;
                  case RESULT_CANCELED:
                      Log.e("Settings", "Result Cancel");
                      Toast.makeText(getApplicationContext(),"GPS disabled",Toast.LENGTH_SHORT).show();
                      break;
              }

              break;
      }

   }

}   

启动应用后,它会显示类似这样的内容

enter image description here

单击“确定”后,我想获取用户的最后一个已知位置。请让我知道如何实现此目标。

谢谢

1 个答案:

答案 0 :(得分:0)

new AlertDialog.Builder(this)
            .setCancelable(false)
            .setMessage("to continue, turn on device location, which uses Google's location service")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
                    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 6000, 10, this);
                    Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    return l;
                }
            })
            .setNegativeButton("NO THANKS", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    finish();
                }
            })
            .create()
            .show();

对于API级别> 23,必须先获得运行时权限,然后才能获取用户的最后一个已知位置