无法从LocationListener获取当前位置

时间:2013-11-13 05:43:34

标签: android

我有一个 LocationService ,它会启动 MainActivity onResume()并停止onDestroy()

@Override
protected void onResume() {
    super.onResume();
    //Start the service using alaram manager
    //If its not running currently
    if (isLocationServiceRunning(this)) {
        am = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent intent = new Intent(this, LocationService.class);
        pi = PendingIntent.getService(this, 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        am.cancel(pi);
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime(), 1 * 60 * 1000, pi);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    if (isLocationServiceRunning(this)) {
        stopService(new Intent(this, LocationService.class));
        if (am != null && pi != null) {
            am.cancel(pi);
        }
    }
}

LocationService.java

public class LocationService extends Service implements LocationListener {

    public static double curLat = 0.0;
    public static double curLng = 0.0;
    private LocationManager mgr;
    private String best;
    private Location location;
    private Location currentBestLocation;
    private static final int TWO_MINUTES = 1000 * 60 * 2;

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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean gps_enabled = mgr
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (gps_enabled) {

            // If GPS is enabled, set criteria as ACCURACY_FINE
            // and get the best provider(which usually will be GPS_PROVIDER)
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);

            best = mgr.getBestProvider(criteria, true);
            // getLastKnownLocation so that user don't need to wait
            location = mgr.getLastKnownLocation(best);
            if (location == null) {
                // request for a single update, and try again.
                // Later will request for updates every 10 mins
                mgr.requestSingleUpdate(criteria, this, null);
                location = mgr
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
            }
            if (location != null) {
                // If the GPS gives a location, update curLat and curLng
                dumpLocation(location);
            } else {
                // If the location is still null, go for NETWORK_PROVIDER
                best = LocationManager.NETWORK_PROVIDER;
                location = mgr.getLastKnownLocation(best);
                if (location != null) {
                    // If the NETWORK gives a location, update curLat and curLng
                    dumpLocation(location);
                }
            }
            // Register the Location Manager for updates, with both the
            // providers
            // Since GPS updates are expensive, we ask update every 10 mins and
            // unregister updates if GPS is disabled in onProviderDisabled
            // callback
            mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                    10 * 60 * 1000, 50, this);
            // NETWORK_PROVIDER updates every 20 secs
            mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                    20 * 1000, 0, this);

            return START_NOT_STICKY;
        } else {
            // If GPS is disables, go with NETWORK_PROVIDER
            best = LocationManager.NETWORK_PROVIDER;
            location = mgr.getLastKnownLocation(best);
            if (location != null) {
                dumpLocation(location);
            }
            // Register NETWORK_PROVIDER for updates every 20 secs
            mgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                    20 * 1000, 0, this);
            return START_NOT_STICKY;
        }
    }

    private void dumpLocation(Location l) {
        // Called to update the curLat and curLng.
        currentBestLocation = l;
        SimpleDateFormat s = new SimpleDateFormat("dd/MM/yyyy:hh:mm:ss",
                Locale.ENGLISH);
        String format = s.format(l.getTime());
        try {
            Geocoder coder = new Geocoder(this);
            List<Address> address;
            Address location = null;
            address = coder.getFromLocation(l.getLatitude(), l.getLongitude(),
                    1);
            location = address.get(0);
        } catch (Exception e) {
            Log.e("Exception while getting address", e.getMessage() + "");
        }
        curLat = l.getLatitude();
        curLng = l.getLongitude();
    }

    @Override
    public void onLocationChanged(Location location) {
        // called when location is changed, since we registered Location
        // Providers
        // for updates
        if (isBetterLocation(location, currentBestLocation)) {
            dumpLocation(location);
        } else {
            Log.d("Not a Better Location", "Ignore");
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // Check if best(the currently being used provider) is not null
        if (best != null) {
            // if best and disabled provider are same, the remove updates
            if ((provider.equalsIgnoreCase(LocationManager.GPS_PROVIDER) && best
                    .equals(LocationManager.GPS_PROVIDER))
                    || provider
                            .equalsIgnoreCase(LocationManager.NETWORK_PROVIDER)
                    && best.equals(LocationManager.NETWORK_PROVIDER)) {
                if (mgr != null) {
                    mgr.removeUpdates(this);
                }
            }
        }
    }

    @Override
    public void onProviderEnabled(String provider) {
        // This will be taken care in the onStartCommand where if gps_enabled
        // case is used.
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // No need to care about, because any thing like OUT_OF_SERVICE occurs,
        // location being fetched will be null and such cases are handled above.
        if ((provider.equals(LocationManager.GPS_PROVIDER))
                && (LocationProvider.OUT_OF_SERVICE == status)) {
            if (mgr != null) {
                mgr.removeUpdates(this);
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // triggered when we call stopService(LocationService);
        // which is done in onDestroy of MainActivity
        // Because LocationService must be stopped
        // when application is closed to avoid data usage
        if (mgr != null) {
            mgr.removeUpdates(this);
        }
    }

    protected boolean isBetterLocation(Location location,
            Location currentBestLocation) {
        if (currentBestLocation == null) {
            // A new location is always better than no location
            return true;
        }

        // Check whether the new location fix is newer or older
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
        boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
        boolean isNewer = timeDelta > 0;

        // If it's been more than two minutes since the current location, use
        // the new location
        // because the user has likely moved
        if (isSignificantlyNewer) {
            return true;
            // If the new location is more than two minutes older, it must be
            // worse
        } else if (isSignificantlyOlder) {
            return false;
        }

        // Check whether the new location fix is more or less accurate
        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
                .getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;

        // Check if the old and new location are from the same provider
        boolean isFromSameProvider = isSameProvider(location.getProvider(),
                currentBestLocation.getProvider());

        // Not significantly newer or older, so check for Accuracy
        if (isMoreAccurate) {
            // If more accurate return true
            return true;
        } else if (isNewer && !isLessAccurate) {
            // Same accuracy but newer, return true
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate
                && isFromSameProvider) {
            // Accuracy is less (not much though) but is new, so if from same
            // provider return true
            return true;
        }
        return false;
    }

    // Checks whether two providers are the same
    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }
}

服务肯定会按预期启动和停止,我可以在日志中看到位置详细信息,这很好。

问题是,当我移动到完全不同的位置(300英里)时, curLat curLng 值仍然保持旧的值,当我打开应用

是因为我在设备运行时没有运行服务(因为我的应用程序没有运行)?

因为当我打开其他应用程序(如FourSquare(获取正确的位置))然后重新打开我的应用程序时,它会显示正确的位置。

我还应该做些什么来正确刷新位置。

10 个答案:

答案 0 :(得分:3)

如果您希望将位置放在前台,您的代码看起来非常好。我已经深入了解并且知道在onDestroy你已经停止了服务和警报。因此,当当前应用程序进入后台并且系统调用onDestroy时,代码无法更新后台中的位置。当你再次启动应用程序时,它会启动服务并且第一次获得缓存的旧位置。

当其他应用程序更新位置时,您将根据mgr.getLastKnownLocation(best)的文档获取该位置。

因此,要解决此问题,请不要在此处使用警报以重复方式启动服务或将其破坏。

只需启动服务,然后在onStartCommand中请求更新位置。如果您想摆脱位置更新,请使用removeLocationUpdates(LocationListener)

此处给出了示例http://developer.android.com/training/location/receive-location-updates.html

答案 1 :(得分:3)

我认为你的问题在这里

best = mgr.getBestProvider(criteria, true);
// getLastKnownLocation so that user don't need to wait
location = mgr.getLastKnownLocation(best);
if (location == null) {
     // request for a single update, and try again.
     // Later will request for updates every 10 mins
     mgr.requestSingleUpdate(criteria, this, null);
     location = mgr
             .getLastKnownLocation(LocationManager.GPS_PROVIDER);
 }

因为先前位置location = mgr.getLastKnownLocation(best);会返回该位置而不会启动提供商(请参阅the android documentation。所以该位置不为空且mgr.requestSingleUpdate(criteria, this, null);永远不会跑。

要获取最新的位置数据,必须启动提供程序。

所以纠正可能是:

best = mgr.getBestProvider(criteria, true);
// getLastKnownLocation so that user don't need to wait
mgr.requestSingleUpdate(best, this, null);
location = mgr.getLastKnownLocation(best);

此外,我不确定是否有意,但即使GPS数据可用且更准确,此服务也将使用网络提供商(由于GPS更新和数据过时选择了10分钟和2分钟。

P.S。是否有特定原因您不想使用属于Google Play服务的FusedLocationProvider?我发现它更简单,它应该针对选定的最佳供应商进行优化并节省电池。

答案 2 :(得分:1)

我最好的猜测是转储&#34; isBetterLocation&#34;并尝试没有它看看会发生什么。根据这些检查(相当复杂),我认为错误是在#34; isSignificantlyOlder&#34;或者在最后一个返回语句中(否则你会得到新的位置,对吗?)

您是否调试过它以检查当前逻辑是否正确,如果是,是在什么距离?

答案 3 :(得分:1)

以下是使用Google Play服务接收位置更新的示例

这是MyActivity类

public class MyActivity extends Activity implements
    ConnectionCallbacks, OnConnectionFailedListener {

public static final int PLAY_SERVICES_NOT_AVAILABLE_REQUEST = 9000;
public static final int CONNECTION_FAILED_REQUEST = 1000;

private LocationClient mLocationClient;
private LocationRequest mLocationrequest;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_myactivity);

    LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    mLocationClient = new LocationClient(this, this, this);

    boolean isGPSEnabled = mLocationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    boolean isNetworkEnabled = mLocationManager
            .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

    Toast.makeText(this, "GPS: " + isGPSEnabled, Toast.LENGTH_SHORT).show();
    Toast.makeText(this, "Network: " + isNetworkEnabled, Toast.LENGTH_SHORT)
            .show();

    if (isGooglePlayServicesAvailable()) {
        mLocationClient.connect();
    } else {
        // play services not available
    }
}

private void defineLocationRequest() {
    mLocationrequest = new LocationRequest();
    mLocationrequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(5000);
}

private PendingIntent getCallBackIntent() {
    return PendingIntent
            .getService(getApplicationContext(), 0, new Intent(this,
                    MyIntentService.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
}

private boolean isGooglePlayServicesAvailable() {
    int resultCode = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);

    if (resultCode == ConnectionResult.SUCCESS) {
        Log.d("Car Tracking", "play services available.");
        return true;
    } else {
        Log.d("Car Tracking", "play services not available(resultCode:) "
                + resultCode);
        GooglePlayServicesUtil.getErrorDialog(resultCode, this,
                PLAY_SERVICES_NOT_AVAILABLE_REQUEST).show();
        return false;
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // TODO Auto-generated method stub
    switch (requestCode) {

    case PLAY_SERVICES_NOT_AVAILABLE_REQUEST:
        if (resultCode == Activity.RESULT_OK) {
            // check again
        }
        break;

    case CONNECTION_FAILED_REQUEST:
        if (resultCode == Activity.RESULT_OK) {
            // try to connect LocationClient Againg
        }

        break;
    }

}

@Override
public void onConnectionFailed(ConnectionResult arg0) {
    // TODO Auto-generated method stub
    if (arg0.hasResolution()) {
        try {
            arg0.startResolutionForResult(this, CONNECTION_FAILED_REQUEST);
        } catch (SendIntentException e) {
            Log.d("TAG",
                    "Exception in resolving connection failed: "
                            + e.toString());
        }

    }
}

@Override
public void onConnected(Bundle arg0) {
    // TODO Auto-generated method stub
    defineLocationRequest();
    mLocationClient.requestLocationUpdates(mLocationrequest,
            getCallBackIntent());

}

@Override
public void onDisconnected() {
    // TODO Auto-generated method stub

}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    mLocationClient.removeLocationUpdates(getCallBackIntent());
    super.onDestroy();
}

}

现在,这是MyIntentService类的onHandleIntent方法。

protected void onHandleIntent(Intent intent) {
    // TODO Auto-generated method stub
    if (intent != null) {

        Bundle extra = intent.getExtras();
        Location location = (Location) extra
                .get(LocationClient.KEY_LOCATION_CHANGED);

}

此处,位置对象将为您提供最新的位置更新

同时添加

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
你的清单中的

答案 4 :(得分:0)

您可以使用Google Play服务中的LocationClient,它易于使用并且经过验证非常高效。 以下是example

的链接

答案 5 :(得分:0)

答案 6 :(得分:0)

使用融合位置提供程序(自4.2以来可用的新功能 - https://developer.android.com/google/play-services/location.html) - 它只是获取当前快速位置并发送更新。

示例:http://www.motta-droid.com/2013/11/location-requests-for-your-app-how-to.html

只需在服务中运行上面的单例,并根据需要调整位置更新参数。

您应该关心的唯一问题 - 如果它根本无法确定您当前的位置。例如,如果您的设备只有GPS位置提供商,那么您就在室内。

答案 7 :(得分:0)

我观察了您的代码..您正在更新位置,但您没有收到更新的位置信息。以下是如何从服务中获取位置的代码

// Send an Intent with an action named "custom-event-name". The Intent sent
// should
// be received by the ReceiverActivity.
private static void sendMessageToActivity(Location l, String msg) {
    Intent intent = new Intent("GPSLocationUpdates");
    // You can also include some extra data.
    intent.putExtra("Status", msg);
    Bundle b = new Bundle();
    b.putParcelable("Location", l);
    intent.putExtra("Location", b);
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

在您的主要活动中或必须接收位置信息写下此代码。

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(
            mMessageReceiver, new IntentFilter("GPSLocationUpdates"));

private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {         
        Bundle b = intent.getBundleExtra("Location");
        lastKnownLoc = (Location) b.getParcelable("Location");
        if (lastKnownLoc != null) {
            tvLatitude.setText(String.valueOf(lastKnownLoc.getLatitude()));
            tvLongitude
                    .setText(String.valueOf(lastKnownLoc.getLongitude()));              
        }           
    }
};

我希望这会奏效......

答案 8 :(得分:0)

我不介意等待GPS实现首次修复,这可能会对您有所帮助。如果最近发现修复,第一次修复只需几秒钟。

我已经实现了一些代码,只要有来自http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/的GPSTracker的第一次修复和位置更改,就会发送回调。

通过此实现,您可以:

private GPSTracker gps;
private FirstFixListener firstFixListener;
private LocationUpdateListener locationUpdateListener;

private void startGPS() {
    gps = GPSTracker.getInstance(context);
    // create listeners
    firstFixListener = new MyFirstFixListener();
    locationUpdateListener = new MyLocationUpdateListener();
    // start the gps
    gps.startUsingGPS(firstFixListener, locationUpdateListener);
}

    private void stopGPS() {
        // stop the gps and unregister callbacks
        gps.stopUsingGPS(firstFixListener, locationUpdateListener);
    }

private class MyFirstFixListener implements FirstFixListener {

    @Override
    public void onFirsFixChanged(boolean hasGPSfix) {
        if (hasGPSfix == true) {
            // accurate position
            Location position = gps.getLocation();
        }

    }

}

private class MyLocationUpdateListener implements LocationUpdateListener {

    @Override
    public void onLocationChanged(Location location) {
        // hand you each new location from the GPS
        // you do not need this if you only want to get a single position
    }

}

这是我对GPSTracker的实现:

public class GPSTracker extends Service implements LocationListener {

private static final String TAG = "GPSTracker";

/**
 * Register to receive callback on first fix status
 * 
 * @author Morten
 * 
 */
public interface FirstFixListener {

    /**
     * Is called whenever gps register a change in first-fix availability
     * This is valuable to prevent sending invalid locations to the server.
     * 
     * @param hasGPSfix
     */
    public void onFirsFixChanged(boolean hasGPSfix);
}

/**
 * Register to receive all location updates
 * 
 * @author Morten
 * 
 */
public interface LocationUpdateListener {
    /**
     * Is called every single time the GPS unit register a new location
     * The location param will never be null, however, it can be outdated if hasGPSfix is not true.
     *  
     * @param location
     */
    public void onLocationChanged(Location location);
}

private Context mContext;

// flag for GPS status
private List<FirstFixListener> firstFixListeners;
private List<LocationUpdateListener> locationUpdateListeners;
boolean isGPSFix = false;
boolean isGPSEnabled = false;
private GPSFixListener gpsListener;

// flag for GPS status
boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude
long mLastLocationMillis;

private boolean logLocationChanges;

// Declaring a Location Manager
protected LocationManager locationManager;

/** removed again as we need multiple instances with different callbacks **/
private static GPSTracker instance;

public static GPSTracker getInstance(Context context) {
    if (instance != null) {
        return instance;
    }
    return instance = new GPSTracker(context);
}

private GPSTracker(Context context) {
    this.mContext = context;
    gpsListener = new GPSFixListener();
    firstFixListeners = new ArrayList<GPSTracker.FirstFixListener>();
    locationUpdateListeners = new ArrayList<GPSTracker.LocationUpdateListener>();
}

public boolean hasGPSFirstFix() {
    return isGPSFix;
}

private void addFirstFixListener(FirstFixListener firstFixListener) {
    this.firstFixListeners.add(firstFixListener);
}

private void addLocationUpdateListener(
        LocationUpdateListener locationUpdateListener) {
    this.locationUpdateListeners.add(locationUpdateListener);
}

private void removeFirstFixListener(FirstFixListener firstFixListener) {
    this.firstFixListeners.remove(firstFixListener);
}

private void removeLocationUpdateListener(
        LocationUpdateListener locationUpdateListener) {
    this.locationUpdateListeners.remove(locationUpdateListener);
}

public void setLogLocationChanges(boolean logLocationChanges) {
    this.logLocationChanges = logLocationChanges;
}

public Location getLocation() {
    return location;
}

private Location startLocationListener() {
    canGetLocation = false;

    try {
        locationManager = (LocationManager) mContext
                .getSystemService(Service.LOCATION_SERVICE);

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

        if (isGPSEnabled) {
            if (location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.GPS_PROVIDER, 0, 0, this);
                locationManager.addGpsStatusListener(gpsListener);
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        } else {
            showSettingsAlert();
        }

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

    return location;
}

public void stopUsingGPS(FirstFixListener firstFixListener,
        LocationUpdateListener locationUpdateListener) {
    if (firstFixListener != null)
        removeFirstFixListener(firstFixListener);
    if (locationUpdateListener != null)
        removeLocationUpdateListener(locationUpdateListener);

    stopUsingGPS();
}

/**
 * Stop using GPS listener Calling this function will stop using GPS in your
 * app
 * */
public void stopUsingGPS() {
    Log.d("DEBUG", "GPS stop");
    if (locationManager != null) {
        locationManager.removeUpdates(GPSTracker.this);
        location = null;

        if (gpsListener != null) {
            locationManager.removeGpsStatusListener(gpsListener);
        }

    }
    isGPSFix = false;
    location = null;
}

public void startUsingGPS(FirstFixListener firstFixListener,
        LocationUpdateListener locationUpdateListener) {
    Log.d("DEBUG", "GPS start");
    if (firstFixListener != null)
        addFirstFixListener(firstFixListener);
    if (locationUpdateListener != null)
        addLocationUpdateListener(locationUpdateListener);

    startLocationListener();
}

/**
 * Function to get latitude
 * */
public double getLatitude() {
    if (location != null) {
        latitude = location.getLatitude();
    } else {
        Log.e("GPSTracker", "getLatitude location is null");
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude() {
    if (location != null) {
        longitude = location.getLongitude();
    } else {
        Log.e("GPSTracker", "getLongitude location is null");
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * 
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog On pressing Settings button will
 * lauch Settings Options
 * */
public void showSettingsAlert() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS settings");

    // Setting Dialog Message
    alertDialog
            .setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(
                            Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    mContext.startActivity(intent);
                }
            });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    // Showing Alert Message
    alertDialog.show();
}

@Override
public void onLocationChanged(Location location) {
    if ( location == null)
        return;

    this.location = location;



    mLastLocationMillis = SystemClock.elapsedRealtime();
    canGetLocation = true;
    if (isGPSFix) {


        if (locationUpdateListeners != null) {
            for (LocationUpdateListener listener : locationUpdateListeners) {
                listener.onLocationChanged(location);
            }
        }
    }

}

@Override
public void onProviderDisabled(String provider) {
    canGetLocation = false;
}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}

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

private boolean wasGPSFix = false;

// http://stackoverflow.com/questions/2021176/how-can-i-check-the-current-status-of-the-gps-receiver
// answer from soundmaven
private class GPSFixListener implements GpsStatus.Listener {
    public void onGpsStatusChanged(int event) {
        switch (event) {
        case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
            isGPSFix = (SystemClock.elapsedRealtime() - mLastLocationMillis) < 3000;

            if (isGPSFix != wasGPSFix) { // only notify on changes
                wasGPSFix = isGPSFix;
                for (FirstFixListener listener : firstFixListeners) {
                    listener.onFirsFixChanged(isGPSFix);
                }
            }

            break;
        case GpsStatus.GPS_EVENT_FIRST_FIX:
            // Do something.



            break;
        }
    }
}
}

答案 9 :(得分:0)

我正在使用此代码来定位我的位置并且它工作正常。

        initilizeMap();
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if(isGPSEnabled==true){
        if (!isGPSEnabled && !isNetworkEnabled) {

        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        400,
                        1000, this);
                Log.d("Network", "Network Enabled");
                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,
                            400,
                            1000, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

        onLocationChanged(location);
        MarkerOptions marker = new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude())).title("Vous êtes ici");
        googleMap.addMarker(marker);


        }


       private void initilizeMap() {
    if (googleMap == null) {
       SupportMapFragment sp =(SupportMapFragment)           getSupportFragmentManager().findFragmentById(
                R.id.map);
       googleMap=sp.getMap();

        // check if map is created successfully or not
        if (googleMap == null) {
            Toast.makeText(getApplicationContext(),
                    "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}

@Override
protected void onResume() {
    super.onResume();
    initilizeMap();
}

public void onLocationChanged(Location location) {

    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 12);
    googleMap.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);

}

我希望这会对你有所帮助。祝你好运