简体   繁体   English

Android FusedLocationProviderClient 无法提供 LastLocation 和 LocationUpdates

[英]Android FusedLocationProviderClient cannot give LastLocation and LocationUpdates

I am new to android studio but I try my best to tell you what my problem is.我是 android 工作室的新手,但我尽力告诉你我的问题是什么。 Currently, I am building an app that relies on location updates and before the app asks regularly for location updates I want to get the last known location.目前,我正在构建一个依赖位置更新的应用程序,并且在应用程序定期询问位置更新之前,我想获取最后一个已知位置。 I read through a lot of posts and instructions and came up with this code.我阅读了很多帖子和说明,并想出了这段代码。 However, this leads to a pretty strange behavior.但是,这会导致一种非常奇怪的行为。 Sometimes it is able to give me the last known location when I opened another app like google maps before which relies on GPS and sometimes this does not work.有时,当我打开另一个依赖于 GPS 的应用程序(如谷歌地图)时,它可以给我最后一个已知位置,有时这不起作用。 I do not get why it fails, so I hope you guys can help me with that.我不明白为什么它会失败,所以我希望你们能帮助我。 The Permission is given in the manifest btw.顺便说一句,清单中给出了许可。

public class MainActivity extends AppCompatActivity {

    FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest locationRequest;
    LocationCallback locationCallBack;
    private TextView locTester;
    private static final int PERMISSIONS_FINE_LOCATION = 99;

     @RequiresApi(api = Build.VERSION_CODES.O)
     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locTester = findViewById(R.id.locTester);

        locationRequest = LocationRequest.create();
        locationRequest.setInterval(30000);
        locationRequest.setFastestInterval(30000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        locationCallBack = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Location location = locationResult.getLastLocation();
                locTester.setText(location.toString());
            }
        };

        startLocationUpdate();
     }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case PERMISSIONS_FINE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    updateGPS();
                } else {
                    Toast.makeText(this, "This app requires permission to the GPS", Toast.LENGTH_LONG).show();
                    finish();
                }
        }
    }
    private void updateGPS() {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    Geocoder geocoder = new Geocoder(MainActivity.this);
                    try {
                        List<Address> address = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
                        Log.w("location",address.get(0).getAddressLine(0));
                    } catch (Exception e) {
                        Log.w("location","Could not locate your phone");
                    }
                }
            });
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
            }
        }
    }

    private void startLocationUpdate() {
        updateGPS();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack,null);
            Log.w("location","location is being tracked");
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
            }
        }
    }

}

I am new to android studio but I try my best to tell you what my problem is.我是 android 工作室的新手,但我尽力告诉你我的问题是什么。 Currently, I am building an app that relies on location updates and before the app asks regularly for location updates I want to get the last known location.目前,我正在构建一个依赖位置更新的应用程序,并且在应用程序定期询问位置更新之前,我想获取最后一个已知位置。 I read through a lot of posts and instructions and came up with this code.我阅读了很多帖子和说明,并想出了这段代码。 However, this leads to a pretty strange behavior.但是,这会导致一种非常奇怪的行为。 Sometimes it is able to give me the last known location when I opened another app like google maps before which relies on GPS and sometimes this does not work.有时,当我打开另一个依赖于 GPS 的应用程序(如谷歌地图)时,它可以给我最后一个已知位置,有时这不起作用。 I do not get why it fails, so I hope you guys can help me with that.我不明白为什么它会失败,所以我希望你们能帮助我。 The Permission is given in the manifest btw.顺便说一句,清单中给出了许可。

public class MainActivity extends AppCompatActivity {

    FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest locationRequest;
    LocationCallback locationCallBack;
    private TextView locTester;
    private static final int PERMISSIONS_FINE_LOCATION = 99;

     @RequiresApi(api = Build.VERSION_CODES.O)
     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        locTester = findViewById(R.id.locTester);

        locationRequest = LocationRequest.create();
        locationRequest.setInterval(30000);
        locationRequest.setFastestInterval(30000);
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        locationCallBack = new LocationCallback() {
            @Override
            public void onLocationResult(@NonNull LocationResult locationResult) {
                super.onLocationResult(locationResult);
                Location location = locationResult.getLastLocation();
                locTester.setText(location.toString());
            }
        };

        startLocationUpdate();
     }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case PERMISSIONS_FINE_LOCATION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    updateGPS();
                } else {
                    Toast.makeText(this, "This app requires permission to the GPS", Toast.LENGTH_LONG).show();
                    finish();
                }
        }
    }
    private void updateGPS() {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(MainActivity.this);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationProviderClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    Geocoder geocoder = new Geocoder(MainActivity.this);
                    try {
                        List<Address> address = geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
                        Log.w("location",address.get(0).getAddressLine(0));
                    } catch (Exception e) {
                        Log.w("location","Could not locate your phone");
                    }
                }
            });
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
            }
        }
    }

    private void startLocationUpdate() {
        updateGPS();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallBack,null);
            Log.w("location","location is being tracked");
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_FINE_LOCATION);
            }
        }
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM