簡體   English   中英

通過對話框啟用位置服務時,獲取最后一個位置不起作用

[英]Get last location is not working when location services are enabled through the dialog box

如果我在啟用位置服務的情況下啟動 Activity,該應用程序能夠檢索我上次的位置坐標。 但是,如果活動在未啟用定位服務的情況下啟動,並且我單擊獲取當前位置按鈕,則會顯示一個對話框,允許我啟用定位服務。 一旦啟用,我仍然無法檢索我的最后一個位置坐標 - 根據我的代碼中的 Toast,我返回“當前位置為空”。 我見過其他線程,但這些解決方案似乎對我現有的代碼過於干擾。 我非常希望對現有代碼進行小幅調整可以解決我的問題。

public class ExploreFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mapView;
    private Location currentLocation;
    private FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;
    private String apiKey = "[KEY REMOVED]";
    private PlacesClient placesClient;
    private LatLng userLocation;
    FloatingActionButton buttonCurrentLocation;
    private LocationManager locationManager;

    public View onCreateView(@NonNull final LayoutInflater inflater, ViewGroup container, final Bundle savedInstanceState) {
        final View view = inflater.inflate(R.layout.fragment_explore, null, false);

        locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
        lastLocation();

        buttonCurrentLocation = view.findViewById(R.id.buttonCurrentLocation);
        buttonCurrentLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                    locationDialog();
                } else {
                    if (currentLocation != null) {
                        userLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
                        mapView.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15.0f));
                    } else {
                        Toast.makeText(getContext(), "Current location is null", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        return view;
    }

    public void onMapReady(final GoogleMap googleMap) {
        mapView = googleMap;

        if (currentLocation != null) {
            userLocation = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
            mapView.animateCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15.0f));
        }
    }

    private void locationDialog() {
        new AlertDialog.Builder(getContext())
                .setTitle("No GPS signal found")  // GPS not found
                .setMessage("To continue, turn on device location") // Want to enable?
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                    }
                })
                .setNegativeButton("No, thanks", null)
                .show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    lastLocation();
                }
                break;
        }
    }

    private void lastLocation() {
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]
                    {Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
        }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
                        .findFragmentById(R.id.mapView);
                mapFragment.getMapAsync(ExploreFragment.this);
                if (location != null) {
                    currentLocation = location;
                }
            }
        });
    }
}

在以下情況下,位置對象可能為null

  • 定位在設備設置中已關閉。 即使先前檢索了最后一個位置,結果也可能為空,因為禁用位置也會清除緩存。

  • 設備從未記錄其位置,這可能是新設備或已恢復出廠設置的設備的情況。

  • 設備上的 Google Play 服務已重新啟動,並且在服務重新啟動后沒有請求位置的活動 Fused Location Provider 客戶端。 為了避免這種情況,您可以創建一個新客戶端並自己請求位置更新。 有關更多信息,請參閱接收位置更新。

看來您遇到了第三種情況:)

文檔中的更多信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM