onLocationChanged not called on some devices

后端 未结 7 1496
悲哀的现实
悲哀的现实 2020-12-30 01:38

This is a question which has been asked numerous times but I could not find a solution that always works.

I am developing an application using the Fused location pro

7条回答
  •  春和景丽
    2020-12-30 02:17

    I observed same behavior on Galaxy Nexus and recognized two things causing onLocationChanged() to not being called. There are

    1. Corresponding location source is not enabled in System Settings. For PRIORITY_HIGH_ACCURACY the GPS satellites must be enabled, for PRIORITY_BALANCED_POWER_ACCURACY Wi-Fi & mobile network location must be enabled.

    2. Even for the enabled location sources there can be no valid location information available. For instance, PRIORITY_HIGH_ACCURACY source is enabled, but there is no (or not good) GPS reception (e.g. device is inside a building). Or PRIORITY_BALANCED_POWER_ACCURACY source is enabled, but both Wi-Fi and mobile data are switched off. In those cases location cannot be detected and onLocationChanged() will not be called.

    To fix #1 I had to check whether required location sources are enabled even before connecting to Google Services API and if they are switched off, then I notified a user asked him/her to allow location access.

    To solve #2 I decided to use LocationRequest.setExpirationDuration(). I set timeout at about 10 seconds, and immediately after calling requestLocationUpdates() I post a callback delayed by same 10 seconds. If delayed callback is called before requestLocationUpdates(), this means location cannot be detected due to reason #2. I do three retries and then show user an error message.

    Android documentation is not great at this place, that's why I hope this helps.

提交回复
热议问题