Android app set location

Глубокое погружение в определение местоположения

Этот пост является переводом топика из блога android-developers. Далее повествование ведется от Рето Майера, автора книги Professional Android 2 Application Development. Он пишет о том, как можно улучшить приложения, использующие местоположение, в смысле кэширования результатов, скорости работы и так далее.

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

Вместо того, чтобы грозить кулаком в небо, я написал open-source приложение, которое включает в себя советы и рекомендации по сокращению времени между открытием приложения и просмотром актуальной информации о близлежащих местах, вкупе с разумным обеспечением offline режима работы. И всё это, сохраняя использование аккумулятора на возможном минимуме.

Покажи мне код!

Вы можете проверить мой проект Android Protips for Location. Не забудьте прочесть Readme.txt, чтобы успешно скомпилировать и запустить приложение.

Что оно делает на самом деле?

Оно использует Google Places API для реализации базовой функциональности приложений, которые которые используют местоположение для определения списка близлежащих достопримечательностей (точек на карте), позволяют просмотреть их детали, а также проверить или оценить.

Код реализует многие из лучших практик, о которых я подробно рассказал на своей сессии на Google I/O 2011, Android Protips: Advanced Topics for Expert Android Developers (видео). В том числе использование Intent’ов для получения обновлений о местоположении, используя Passive Location Provider, наблюдение за состоянием устройства для изменения частоты обновлений, переключение Receiver’ов во время исполнения приложения, и также используя Cursor Loader.

Приложение написано для Honeycomb, но также может работать и на версия 1.6 и выше.

Теперь у вас есть код, давайте подробнее рассмотрим его

Мой главный приоритет — свежесть: минимизация задержек между открытием приложения и возможностью проверить нужные места, и в то же время минимизировать использование аккумулятора.

Требования:

  • Текущее местоположение должно находиться так быстро, как это возможно
  • Список мест должен обновляться при изменение местоположения
  • Список близлежащих мест должен быть доступен (в деталях) в автономном режиме
  • Отметки также должны быть доступны в автономном режиме
  • Данные о местоположении и другие данные пользователя должны быть правильно обработаны (см. более ранний пост с лучшими практиками )

Свежесть — значит никогда не ждать

Можно значительно сократить время ожидания получения первого приближения к местоположению, путём выбора последнего известного из Location Manager’a каждый раз, когда приложение переходит в активный режим.

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

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

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

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

Читайте также:  Гонки по трассе для андроид

Отметим также, что этот фрагмент кода показывает GingerbreadLastLocationFinder, который использует метод requestSingleUpdate для получения единоразового обновления местоположения. Эта функциональность не была доступна до Gingerbread — проверьте LegacyLastLocationFinder, посмотрите как я реализовал такую же функциональность для более ранних версий Android.

singleUpdateReceiver передает полученное обновление назад к вызывающему классу через слушателя Location Listener.

Используйте Intent’ы для получения обновлений местоположения

Получив наиболее точную/своевременную оценку текущей позиции, мы также хотим получать её обновления.

Класс PlacesConstants включает в себя набор значений, которые определяют частоту обновления местоположения. Настройте их, чтобы убедиться, что обновления приходят так часто, как это требуется.

Следующий шаг — запросить обновление местоположения от Location Manager. В следующем фрагменте кода, взятом из GingerbreadLocationUpdateRequester мы можем передать критерии, используемые для определения — какой Location Manager будет запрашивать обновления напрямую в вызове метода requestLocationUpdates.

Обратите внимание, что мы передаём Pending Intent, а не Location Listener.

Вообще, я предпочитаю использовать Location Listener’ов, потому что они предоставляют гибкость в регистрации приёмников в нескольких Activity или Сервисах, или напрямую в манифесте.

В этом приложении, новое местоположение означает обновленный список близлежащих мест. Это происходит через сервисы, которые отправляют запросы к серверу и обновляют Контент-провайдер, который заполняет список мест.

Так как изменение местоположения напрямую не обновляет UI, то имеет смысл создавать и регистрировать связанный LocationChangedReceiver в манифесте, а не в Activity.

LocationChangedReceiver извлекает местоположение из каждого обновления и запускает сервис PlaceUpdateService, чтобы обновить базу близлежащих мест.

Получение данных во время автономной работы

Чтобы добавить поддержку режима offline, мы начнём с кэширования результатов поиска по PlacesContentProvider и PlaceDetailsContentProvider.

Также, при определенный обстоятельствах нужно проводить выборку сведений о местоположении. Этот фрагмент кода из сервиса PlacesUpdateService демонстрирует, как предварительная выборка включается для ограниченного количества мест.

Обратите внимание на то, что предварительная выборка данных потенциально выключается при низком заряде аккумулятора.

Похожая техника используется для реализации offline отметок.

Оптимизация времени работы аккумулятора: умные сервисы и использование состояния устройства для переключения ресиверов

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

Если соединения нет, то ActiveLocationChangedReceiver и PassiveLocationChangedReceiver выключаются, а ConnectivityChangedReceiver включается.

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

Мониторинг состояния аккумулятора для уменьшения функциональности и экономии энергии

Когда телефон на последних 15%, то большинство приложений не работает, для того чтобы сохранить заряд. Мы можем зарегистрировать ресиверов в манифесте, чтобы выдавать предупреждение, когда устройство входит или выходит из состояния низкой батареи.

Этот фрагмент из PowerStateChangedReceiver выключает PassiveLocationChangedReceiver всякий раз, когда устройство переходит в состояние низкого аккумулятора и включает его, когда заряд в порядке.

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

Источник

How to Change Your GPS Location on Android [2021 Guide]

home_icon Created with Sketch.

Home > Change Location > How to Change Your GPS Location on Android [2021 Guide]

February 16, 2021 (Updated: June 21, 2021)

Today, the majority of Android apps access your smartphone’s GPS signal to offer different services. For instance, Google Maps accesses geolocation to provide real-time navigation whereas social media apps (Instagram & Facebook) use it to show nearby friends.В

Similarly, there are several other situations where changing your smartphone’s GPS location will be helpful. So, in this article, we are going to discuss how to change location on Android phone so that you can hide your real whereabouts and access geo-restricted content without any hassle.

Part 1: When You Can Change or Fake Your GPS Location?

Before moving any further, let’s first discuss what are the different scenarios where you’d want to change your smartphone’s GPS location.

Case 1. Get the latest Android Updates

It’s quite frustrating when a new Android OS update is released in other countries but you still have to wait for another 6-7 weeks to download it on your device. Fortunately, there’s a way to get all the latest updates for your Android device, even if they aren’t released in your country yet. You can simply change your GPS location to a place where the updates are already released and install them without any interruption.

Читайте также:  Перепрошивка андроид tv box

Case 2. Improve Your Online Privacy

For some people, privacy is a major concern these days, considering every app knows their daily movement. Since you don’t know how different apps utilize your geolocation data, it’s always a better option to fake GPS location and hide your current whereabouts.

Case 3. Watch the Latest Movies and TV Shows

Online streaming platforms such as Netflix and Amazon Prime Video usually display content according to the user’s current location. But you can still watch TV Shows and movies that aren’t released in your country by changing your GPS location.

Case 4. You Can Get More Matches on Dating Apps

Dating apps such as Tinder access GPS location and display profiles in a limited radius. But, if you couldn’t find the perfect match, even after swiping through hundreds of profiles, you can expand the search results by changing your current location. This is also a great way to meet new people in a different city before moving there.

Case 5. Boost GPS Signals on Your Real Location

Another situation where you’d want to change your smartphone’s location is when it has a weak GPS signal. There are many scenarios where your device may fail to fetch your current location precisely. In this case, you can manually set your exact location using a geo-spoofing app.

Case 6. Prevent Sharing of Location with Social Media Apps

Social media apps such as Facebook and Instagram also access your GPS location to filter content in your feed and customize the user experience. This is another scenario where you can keep your online privacy intact by changing your current location.В

Part 2: The Most Common Ways to Change Your GPS Location on Android

So, now that you know the benefits of using a spoofed location, let’s take a look at how to change location on Android. The ideal way to set up a fake GPS location is to use a geo-spoofing app. You can find dozens of geo spoofing apps on Google Play Store. All these apps offer the same functionality and have the same features as well. So, you can download any of these apps and you’ll be able to change your GPS location easily.

For a quick demonstration, we are going to use Fake GPS Go Joystick. It’s a GPS Joystick app that’ll let you change your current location and virtually control your GPS movement as well.

Step 1 — Go to Google Play Store and search for Fake GPS GO Joystick. Tap the “Install” button to install the app on your smartphone.

Step 2 — Once the app is installed, open the “Settings” menu and select “Location”. Here make sure to change the “Location Mode” to “GPS Only”.

Step 3 — Again, go back to the “Settings Menu” and click “Developer Options”.

Step 4 — Click “Set Mock Location App” and choose “Fake GPS” from the list.

Step 5 — Once you have set the default mock location app, open “GPS GO Joystick” and use the search bar to find a specific location. The pointer will automatically move to the specific location on the map. Finally, click the “Play” button and your device’s location will be changed automatically.

That’s how to change your location on Android using any of the GPS spoofing tools. Now, even though this is a great way to spoof your location, using such geo spoofing apps have a few limitations. For instance, since there are hundreds of such apps, it can become extremely tiring to know which ones are legit. And, secondly if you install a free location spoofing app it’ll only offer limited features. In fact, some of the fake GPS apps on Google Play Store don’t even provide the Joystick feature.

Читайте также:  Systemui controls android 11

Part 3: Best Alternative Location Changer App To Fake Your GPS Location On Android

So, is there any alternative to geo-spoofing apps on PC? The answer is Yes! You can use iMyFone AnyTo for Android to change your current GPS location and replace it with a fake one. It’s a fully-functional location spoofing tool that’ll let you change your GPS location to anywhere in the world. Unliked other apps, you won’t have to directly install AnyTo on your smartphone or even set it as your default “Mock Location” app. You can install it on your PC and control your smartphone’s GPS location easily.

Here are some of the key features of AnyTo for Android that make it the best geo spoofing tool for Android users.

  • Change Your GPS Location to Anywhere in the World instantly
  • Two-Spot and Multi-Spot Modes to virtually control your GPS movement on the map
  • Save locations in the “History” tab for future
  • Find a specific location using its GPS coordinates

Here’s the step-by-step process on how to change your GPS location on Android using AnyTo for Android.

Step 1 — Download and install “AnyTo For Android” on your PC. Launch the appВ and click “Get Started”.

Step 2 — Connect your device to the computer and wait for the tool to recognize it.

Step 3 — Once the device gets recognized, you’ll see a map on your screen.

Step 4 — Now, choose “Teleport Mode” from the top-right corner and enter a location name in the search bar. You can also find a specific location using its GPS coordinates.

Step 5 — The pointer will move to the selected location automatically. Finally, click “Move” to set it as your current location.

Now, you can use any of the apps on your smartphone and they won’t be able to track your original location at all.

Part 4: Other FAQs about Changing Location on Android

1. Can Fake GPS be Detected?

While it’s not easy to detect if you’re using a fake GPS location or not, it’s always a good strategy to be wise with your approach. For instance, if you are playing Pokemon Go by changing your GPS location, make sure to avoid taking bigger location jumps too frequently. This will trigger the Pokemon GO’s server to detect something is fishy and you might even get your account banned permanently. Also, if you want to avoid getting caught, always ensure to use a professional geo spoofing tool such an AnyTO for Android.

2. Should I Turn Off Location Services on my Android phone?

Ideally, it’s not a wise strategy to disable location services on your Android phone because you won’t be able to use apps such as Google Maps or Tinder. However, if you are concerned about your privacy, you can change your GPS location using a gps spoofing app. This will allow you to hide your original location and use all the geo-services at the same time.

3. Does Airplane Mode Turn Off location?

When you enable Airplane Mode on your device, it’ll only disconnect from network services. As far as location is concerned, Airplane Mode will not turn-off location at all. Instead, if you want to stop third-party apps from tracking your whereabouts, it would be better to use a dedicated location spoofing tool.

Источник

Оцените статью