如何更好地处理GPS定位和android

时间:2014-03-11 20:16:21

标签: android gps locationmanager android-location

我有一个包含listview的片段,它检索用户位置,然后根据用户位置更新列表视图。

我的代码存在的问题是,它似乎抓住了位置更新列表,然后不断更新。并重新加载列表,几乎到了烦恼的程度。这是我的代码:

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();
    }



}

5 个答案:

答案 0 :(得分: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" />

答案 1 :(得分:0)

Here是一个关于GPS定位的重要帖子,以及如何经常检查它。 (在那个例子中30分钟)

您还可以查看Timer设置重复调用方法,以便以您想要的间隔获取位置。

答案 2 :(得分:0)

虽然它可能对您的需求有点强大,但请查看Fused Location Provider。就Android中的位置管理器而言,这是非常具有革命性的。它允许您执行某些操作,例如设置最大和最小间隔时间以及非常直接的关闭实现。我从这个例子开始我的第一次运行并且它工作得非常好(我试图做相反的事情,我需要每5秒更新一次,其中Android在30-45秒内进行更新):

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

答案 3 :(得分:0)

您应该从代码中的某个位置删除gps中的更新(假设在您使用用户的当前本地时可以执行此操作),因此请调用locationManager.removeUpdates(this);在您有合适的位置后,在onLocationChanged()方法内部。

答案 4 :(得分:0)

我为此目的使用了单独的服务,并在其中实现了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");
    }
}