簡體   English   中英

Android Location Listener無法啟動

[英]Android Location Listener not firing

我正在嘗試檢測用戶的當前位置何時在我的android應用程序中更改。 但是不會觸發onLocationChanged。 我試圖在Fragment btw中實現這一點。

分段:

public class Fragment_Map extends Fragment {
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.activity_fragment__live_map, container, false);
        rootView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {

                    return true;
                }
                return false;
            }
        });

        // The minimum time (in miliseconds) the system will wait until checking if the location changed
        int minTime = 1000;
        // The minimum distance (in meters) traveled until you will be notified
        float minDistance = 1;
        // Create a new instance of the location listener
        MyLocationListener myLocListener = new MyLocationListener();
        // Get the location manager from the system
        LocationManager locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        // Get the criteria you would like to use
        Criteria criteria = new Criteria();
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setSpeedRequired(false);
        // Get the best provider from the criteria specified, and false to say it can turn the provider on if it isn't already
        String bestProvider = locationManager.getBestProvider(criteria, false);
        // Request location updates
        locationManager.requestLocationUpdates(bestProvider, minTime, minDistance, myLocListener);

        return rootView;
}

private class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null) {
                Log.d("CHECKLOCA", "fired");
                Toast.makeText(getActivity(), "fired", Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onProviderDisabled(String arg0) {
            // Do something here if you would like to know when the provider is disabled by the user
        }

        @Override
        public void onProviderEnabled(String arg0) {
            // Do something here if you would like to know when the provider is enabled by the user
        }

        @Override
        public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
            // Do something here if you would like to know when the provider status changes
        }
    }

為什么未更改位置的監聽器觸發? 是因為它是片段嗎? 在黑客馬拉松比賽中,您能幫助我解決這個令人討厭的錯誤嗎?

您可以使用GoogleApiClient請求位置並將優先級設置為PRIORITY_HIGH_ACCURACY 您可以創建Fragment來實現GoogelApiClientcallbacks -然后實例化並連接GoogleAPIClient如下所示:

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

然后,一旦您的客戶端連接到Location Services API,您就可以請求更新:

    public void onConnected(Bundle bundle){
    ...
    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(180000); // update interval - eg (3) minutes 
                LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, myLocListener);

    ...

}

我希望這有幫助。

  1. 像這樣創建界面:

     public interface OnLocationReceived { public void onLocationReceived(LatLng latlong); public void onLocationReceived(Location location); public void onConntected(Bundle bundle); public void onConntected(Location location); } 

    2.把它放在MyLocationListener

     @Override public void onLocationChanged(Location location) { if (!isLocationReceived) { mLocationReceived.onConntected(location); isLocationReceived = true; } if (mLocationReceived != null) { mLocationReceived.onLocationReceived(location); } latLong = getLatLng(location); if (mLocationReceived != null && latLong != null) { mLocationReceived.onLocationReceived(latLong); } } 

也許您的設備無法提供您設置的用於查找位置的條件。可以在onCreateView()中使用以下代碼:

  // flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;

 try {
        locationManager = (LocationManager) getActivity()
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                //updates will be send according to these arguments
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

暫無
暫無

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

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