【问题标题】:How to getLocation after enable GPS from ResolvableApiException(Google services) dialog从 ResolvableApiException(Google 服务)对话框启用 GPS 后如何获取位置
【发布时间】:2018-04-02 11:10:02
【问题描述】:

我正在使用谷歌服务来获取当前位置。

我正在使用这种方法来启用位置:

void enableLoc(Activity activity, int request) {

    LocationRequest mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);


    SettingsClient client = LocationServices.getSettingsClient(activity);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

    task.addOnSuccessListener(activity, locationSettingsResponse -> {
        if (locationSettingsResponse.getLocationSettingsStates().isGpsUsable())
            onGetLocation(activity);
    });

    task.addOnFailureListener(activity, e -> {
        if (e instanceof ResolvableApiException) {
            try {

                Timber.d("Dialog to allow GPS location");
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                ResolvableApiException resolvable = (ResolvableApiException) e;
                resolvable.startResolutionForResult(activity,
                        request);
            } catch (IntentSender.SendIntentException sendEx) {
                // Ignore the error.
            }
        }
    });

}

我从以下位置获取位置:

@SuppressLint("MissingPermission")
 void onGetLocation(Activity activity) {
    FusedLocationProviderClient fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(activity);
    fusedLocationProviderClient.getLastLocation().addOnSuccessListener(location -> {

        //I am getting Null after enabling GPS Location

    });
}

这是我的 onActivityResult 方法:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CHECK_SETTINGS && resultCode == RESULT_OK){
        onGetLocation(this);
    }
}

启用 GPS 定位后,我得到空位置。

【问题讨论】:

    标签: android google-location-services


    【解决方案1】:

    在类下面使用...

    public class LocationActivity extends AppCompatActivity implements View.OnClickListener {
    
        private static final int REQUEST_LOCATION = 1;
    
        Button button;
        TextView textView;
        LocationManager locationManager;
        String lattitude, longitude;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.location_layout);
    
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
    
            textView = findViewById(R.id.text_location);
            button = findViewById(R.id.button_location);
            button.setOnClickListener(this);
    
        }
    
        @Override
        public void onClick(View view) {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                buildAlertMessageNoGps();
    
            } else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                getLocation();
            }
        }
    
    
        private void getLocation() {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission
                    (this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
    
            } else {
                Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    
                Location location1 = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    
                Location location2 = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
    
                if (location != null) {
                    double latti = location.getLatitude();
                    double longi = location.getLongitude();
                    lattitude = String.valueOf(latti);
                    longitude = String.valueOf(longi);
    
                    textView.setText("Your current location is" + "\n" + "Lattitude = " + lattitude
                            + "\n" + "Longitude = " + longitude);
    
                } else if (location1 != null) {
                    double latti = location1.getLatitude();
                    double longi = location1.getLongitude();
                    lattitude = String.valueOf(latti);
                    longitude = String.valueOf(longi);
    
                    textView.setText("Your current location is" + "\n" + "Lattitude = " + lattitude
                            + "\n" + "Longitude = " + longitude);
    
    
                } else if (location2 != null) {
                    double latti = location2.getLatitude();
                    double longi = location2.getLongitude();
                    lattitude = String.valueOf(latti);
                    longitude = String.valueOf(longi);
    
                    textView.setText("Your current location is" + "\n" + "Lattitude = " + lattitude
                            + "\n" + "Longitude = " + longitude);
                    String url = "https://iradivi.com/test/?latitude=" + lattitude + "&longitude=" + longitude;
    
    
                } else {
    
                    Toast.makeText(this, "Unble to Trace your location", Toast.LENGTH_SHORT).show();
    
                }
            }
        }
    
        protected void buildAlertMessageNoGps() {
    
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("Please Turn ON your GPS Connection")
                    .setCancelable(false)
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, final int id) {
                            startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                        }
                    })
                    .setNegativeButton("No", new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog, final int id) {
                            dialog.cancel();
                        }
                    });
            final AlertDialog alert = builder.create();
            alert.show();
        }
    
    }
    

    在清单文件中添加以下依赖项..

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

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2016-09-30
      • 2017-04-05
      • 1970-01-01
      • 2013-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多