如何更好地处理GPS定位和android(How to better handle GPS loca

2019-09-30 07:15发布

我有在它列表视图,检索用户位置的片段,然后更新基于用户位置的列表视图。

我的代码的问题是,它似乎要抢位置更新列表,然后不断更新。 和重装名单,几乎到了一点烦恼。 这里是我的代码:

public class FindBrewery extends Fragment implements LocationListener {

    private TextView latituteField;
    private TextView longitudeField;
    LocationManager locationManager;
    private String provider;


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Context c = getActivity().getApplicationContext();
        locationManager =(LocationManager)activity.getSystemService(Context.LOCATION_SERVICE);

    }



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //todo change view
        View rootView = inflater.inflate(R.layout.beer_location_list,container, false);

        // Get the location manager
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);

        // Initialize the location fields
        if (location != null) {
            System.out.println("Provider " + provider + " has been selected.");
            onLocationChanged(location);
        } else {

        }


        return rootView;
    }




    /* Request updates at startup */
    @Override
    public void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }

    /* Remove the locationlistener updates when Activity is paused */
    @Override
    public void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    public void onLocationChanged(Location location) {
        int lat = (int) (location.getLatitude());
        int lng = (int) (location.getLongitude());
        //latituteField.setText(String.valueOf(lat));
        //longitudeField.setText(String.valueOf(lng));

        //Toast.makeText(this, "Finding your loaction",Toast.LENGTH_SHORT).show();

        //call asycn task for location
        String url = "myURL";

        Log.d("urlTest", url);

        //async task goes here
        new GetNearbyBreweries(this.getActivity()).execute(url);



    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        //Toast.makeText(this, "Enabled new provider " + provider,Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onProviderDisabled(String provider) {
        //Toast.makeText(this, "Disabled provider " + provider,Toast.LENGTH_SHORT).show();
    }



}

Answer 1:

也许你会想试试这个方法:

LocationClient mLocationClient;
LocationRequest mLocationRequest;

@Override
public void onAttach(Activity activity) {
  if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity)) {
    mLocationClient = new LocationClient(activity, activity, activity);

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(5000);
    mLocationRequest.setNumUpdates(1);
    mLocationRequest.setFastestInterval(1000);
  }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
  if (mLocationClient != null) {
    mLocationClient.connect();
  }
}

@Override
protected void onStop() {
  if (mLocationClient != null) {
    if (mLocationClient.isConnected()) {
      mLocationClient.removeLocationUpdates(this);
    }

    mLocationClient.disconnect();
  }
  super.onStop();
}

@Override
public void onConnected(Bundle dataBundle) {
  LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  mLocationClient.requestLocationUpdates(mLocationRequest, this);
}

@Override
public void onLocationChanged(Location location) {
  int lat = (int) (location.getLatitude());
  int lng = (int) (location.getLongitude());

  // post to a handler to update the list items
}

诀窍是在以下几点:

  • 你不使用getLastKnownLocation ,因为它使用的缓存和更多的往往不是返回错误的数据,
  • 您设置setNumUpdates(1)所以你并不需要调用removeLocationUpdates()

不要忘记AndroidManifest权限:

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


Answer 2:

这里是GPS定位以及如何经常检查它的每一个巨大的岗位。 (在该示例中30分钟)

你也可能想看看Timer来反复呼吁设置为你想要的时间间隔获取位置的方法。



Answer 3:

虽然它可能是你需要一个强大的一点,看看一体化位置提供商。 这是非常具有革命性至于在Android上的位置管理云。 它可以让你做某些事情,如设置最大和最小间隔时间,以及一个非常简单的关停实施。 我通过做我的第一次运行从这个例子中,它真的很好(我试图做相反的,我需要的地方的Android在做更新过30-45秒,每5秒更新):

http://www.kpbird.com/2013/06/fused-location-provider-example.html



Answer 4:

您应该删除从GPS更新在你的代码(假设你的情况,当你有从用户目前的位置可能会做)的地方,所以叫locationManager.removeUpdates(本); 在onLocationChanged()方法中,一旦你有你需要一个合适的位置。



Answer 5:

我已经用于此目的的一个单独的服务,并实现GPS涉及它的内部功能。 此服务定位请求,并播放他们回来。 所以,你可以只登记接收器,以获得接收坐标。

LocationService.java

package com.my.package.services;

import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;


public class LocationService extends Service implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener {
    private static final String TAG = LocationService.class.getSimpleName();

    public static final String BROADCAST_ACTION = "com.my.package.LOCATION_UPDATE";

    // Milliseconds per second
    private static final int MILLISECONDS_PER_SECOND = 1000;

    // Update frequency in seconds
    public static final int UPDATE_INTERVAL_IN_SECONDS = 60;

    // Update frequency in milliseconds
    private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;

    // The fastest update frequency, in seconds
    private static final int FASTEST_INTERVAL_IN_SECONDS = 40;

    // A fast frequency ceiling in milliseconds
    private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

    private LocationClient locationClient;

    @Override
    public void onCreate() {
        super.onCreate();

        Log.d(TAG, "Location service created…");

        locationClient = new LocationClient(this, this, this);
        locationClient.connect();
    }

    // Unregister location listeners
    private void clearLocationData() {
        locationClient.disconnect();

        if (locationClient.isConnected()) {
            locationClient.removeLocationUpdates(this);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    // When service destroyed we need to unbind location listeners
    @Override
    public void onDestroy() {
        super.onDestroy();

        Log.d(TAG, "Location service destroyed…");

        clearLocationData();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Calling command…");

        return START_STICKY;
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.d(TAG, "Location Callback. onConnected");

        Location currentLocation = locationClient.getLastLocation();

        // Create the LocationRequest object
        LocationRequest locationRequest = LocationRequest.create();

        // Use power balanced mode
        locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

        // Set the update interval to 5 seconds
        locationRequest.setInterval(UPDATE_INTERVAL);

        // Set the fastest update interval to 1 second
        locationRequest.setFastestInterval(FASTEST_INTERVAL);

        locationClient.requestLocationUpdates(locationRequest, this);

        onLocationChanged(currentLocation);
    }

    @Override
    public void onLocationChanged(Location location) {
        Log.d(TAG, "onLocationChanged");
        Log.d(TAG, "LOCATION: " + location.getLatitude() + ":" + location.getLongitude());

        // Since location information updated, broadcast it
        Intent broadcast = new Intent();

        // Set action so other parts of application can distinguish and use this information if needed
        broadcast.setAction(BROADCAST_ACTION);
        broadcast.putExtra("latitude", location.getLatitude());
        broadcast.putExtra("longitude", location.getLongitude());

        sendBroadcast(broadcast);
    }

    @Override
    public void onDisconnected() {
        Log.d(TAG, "Location Callback. onDisconnected");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.d(TAG, "Location Callback. onConnectionFailed");
    }
}


文章来源: How to better handle GPS location and android