2013-11-13 4 views
1

У меня есть LocationService, который начинается onResume() из MainActivity и останавливает onDestroy().Невозможно получить текущее местоположение LocationListener

@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 (которое получает правильное местоположение), а затем снова открывает мое приложение, оно показывает правильное местоположение.

Что еще нужно сделать, чтобы правильно обновить местоположение.

+0

Почему вы не начинаете свою службу в oncraete, а не в onresume , когда приложение не находится в стеке ОС, оно будет инициализировано, и 1-й вызванный метод будет создан после этого, если приложение будет отдыхать на заднем плане при повторной обработке onresume будет так что попробуйте его в oncreate, а просто в onresume –

+0

Я думаю, islocationservice возвращает false, также попробуйте с возвратом Service.START_STICKY; –

+0

@UsmanKurd 'onCreate()' в конечном итоге вызывает 'onResume()'. Более того, у меня нет проблем при запуске службы. Проблема заключается в том, что служба не обновляет местоположение. –

ответ

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 доступен и более точным (из-за 10 минут и 2-х минутное время, выбранное для обновлений GPS и устаревания данных.

PS Есть ли конкретная причина, по которой вы не хотите использовать FusedLocationProvider, входящий в состав сервисов Google Play? Я нашел, что это проще, и оно, предположительно, оптимизировано для выбранных лучших поставщиков и сохраняющих аккумулятор.

+0

Одним из преимуществ использования платного провайдера является то, что он не полагается на доступные сервисы Google Play. Однако платный провайдер, безусловно, гораздо более функциональный и прост в обращении. – pjco

+0

См. Edit, у этого все еще есть проблемы, и это зависит именно от того, что вам нужно, но это должно помочь –

1

Мое лучшее предположение - дамп «isBetterLocation» и попробуйте без него посмотреть, что произойдет. Основываясь на этих проверках (которые довольно сложны), я думаю, что ошибка заключается либо в «isSignificantlyOlder», либо в последнем заявлении о возврате (в противном случае вы получите новое местоположение, исправьте?)

Вы отлаживали его, чтобы проверить, текущая логика правильная, и если да, то на каких расстояниях?

+0

Я объяснил логику в комментариях. И он отлично работал в соответствии с логикой (сброс местоположения только тогда, когда он был лучше). –

3

Код выглядит отлично, если вы хотите получить местоположение на переднем плане. Я прошел через глубину и узнаю, что в onDestroy вы также остановили службу и сигналы тревоги. следовательно, когда и когда текущее приложение переходит в фоновый режим, и onDestroy вызывается системой, тогда код не обновляет местоположение в фоновом режиме. более того, когда вы снова запускаете приложение, он запустит службу и в первый раз получит более старое место, которое было кэшировано.

, когда другое приложение обновляет местоположение, вы получите это местоположение в соответствии с документацией mgr.getLastKnownLocation(best).

Следовательно, для решения этой проблемы не используйте будильник здесь, чтобы начать обслуживание повторением или уничтожить его.

просто запустите службу и в onStartCommand попросите обновить местоположение. и если вы хотите избавиться от обновлений местоположения, используйте removeLocationUpdates(LocationListener).

примеры приведены здесь http://developer.android.com/training/location/receive-location-updates.html

+0

Согласовано. Если вы работаете как служба, я рекомендую использовать Broacasts для уведомления о действиях. – shkschneider

0

Вы можете использовать LocationClient в Google Play Services, его простой в использовании и проверенный очень эффективный. Вот ссылка на example

1

Вот пример, чтобы получить обновление местоположения с помощью Google Play Services

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

Теперь это метод OnHandleIntent класса MyIntentService.

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"/> 

в манифесте

0

Использование плавленый Location Provider (новый функция доступна с 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

Просто запустите одноточечно выше в службе и настроить обновление местоположения Params с вашими потребностями.

Единственная проблема, о которой вам следует подумать - если она не может определить ваше текущее местоположение вообще. Например, если для вашего устройства доступен только провайдер местоположения GPS, и вы находитесь в помещении.

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

Я надеюсь, что это будет работать ...

0

Я не возражаю ждет GPS, чтобы достигнуть первого исправить это может помочь вам. Первое исправление должно быть в считанные секунды, если исправление найдено недавно.

Я внедрил некоторый код, который отправляет обратный вызов, как только есть первое исправление и нахождение на основе GPSTracker от http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/.

С этой реализации вы можете сделать:

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

} 

Надеюсь, это поможет вам. удачи

Смежные вопросы