为什么此代码(使用FusedLocationProviderClient获取用户的位置)不起作用?

时间:2019-01-24 17:56:57

标签: java android location

我想尽可能准确地找到用户的当前纬度和经度,并将此数据显示在MainActivity的TextView中。但是,应用程序始终返回0.0、0.0作为纬度和经度。

我尝试修复我的AndroidManifest,并手动为该应用赋予适当的位置权限。

public class MainActivity extends AppCompatActivity {
TextView mTextViewLocation ;
boolean permission ;
private FusedLocationProviderClient mFusedLocationClient;
private LocationRequest mLocationRequest;
private LocationCallback mLocationCallback;
private double Latitude ;
private double Longitude ;
@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    setupGPS();
    mTextViewLocation = (TextView)findViewById(R.id.textViewLocation);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setInterval(60000);
    mLocationRequest.setFastestInterval(20000);
    mLocationRequest.setMaxWaitTime(60000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            if (locationResult == null){
                Log.d("Location: GPS","off");
                return;
            }
            for (Location location : locationResult.getLocations()) {
                Log.d("locations : " ,location.getLatitude()+"");
                Latitude = location.getLatitude();
                Longitude = location.getLongitude();
            }
        }
    };
    String s = Latitude + " " + Longitude ;
    mTextViewLocation.setText(s);
}
public void setupGPS() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    SettingsClient client = LocationServices.getSettingsClient(this);
    Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());
    task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            if(PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION)) {
                permission=true;
                mFusedLocationClient.requestLocationUpdates(mLocationRequest,
                        mLocationCallback,null);
            }
            else {
               permission=false;
                AlertDialog.Builder alert=new AlertDialog.Builder(MainActivity.this);
                alert.setTitle("Permission Denied");
                alert.setMessage("You need to enable location permissions for this app.");
                alert.setPositiveButton("Continue", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        permission = true ;
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                608);
                    }
                });
                alert.setNegativeButton("Later", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        permission=false;
                    }
                });
                alert.create().show();
            }
        }
    });
    task.addOnFailureListener(this, new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            if (e instanceof ResolvableApiException) {
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    ResolvableApiException resolvable = (ResolvableApiException) e;
                    resolvable.startResolutionForResult(MainActivity.this,
                            607);
                } catch (IntentSender.SendIntentException sendEx) {
                    // Ignore the error.
                }
            }
        }
    });
}

}

我希望它以纬度和经度显示我的准确位置,但现在只显示“ 0.0 0.0”。

这些是我在AndroidManifest中授予应用程序的权限:

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-feature android:name="android.hardware.location.gps" /> 

我还将它包含在应用程序的Build.gradle中:

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

1 个答案:

答案 0 :(得分:1)

String s = Latitude + " " + Longitude; mTextViewLocation.setText(s);

onLocationResult()方法调用之外。由于mTextViewLocation.setText(s);是在onLocationResult()方法之前调用的,因此您在文本视图中获得错误的值。

以下是获取设备位置的步骤:

  1. 在应用程序级别gradle文件中添加依赖项: implementation com.google.android.gms:play-services-location:16.0.0

  2. 确保在Menifest文件中添加权限:

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

  3. 然后您可以使用以下代码获取位置:


 LocationRequest request = new LocationRequest();
            request.setInterval(10000);
            request.setFastestInterval(5000);
            request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
            FusedLocationProviderClient client = 
         LocationServices.getFusedLocationProviderClient(this);
            int permission = ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION);   
            if (permission == PackageManager.PERMISSION_GRANTED) {   
                    // Request location updates and when an update is 
                    // received, update text view    
                    client.requestLocationUpdates(request, new LocationCallback() {         
                            @Override  
                        public void onLocationResult(LocationResult locationResult) {                           
                            Location location = locationResult.getLastLocation();  
                            if (location != null) {   
                                    // Use the location object to get Latitute and Longitude and then update your text view.  
                            }  
                        }  
                    }, null);  
                }