- Android Turn on GPS programmatically
- How to Change Your GPS Location on Android [2021 Guide]
- Part 1: When You Can Change or Fake Your GPS Location?
- Part 2: The Most Common Ways to Change Your GPS Location on Android
- Part 3: Best Alternative Location Changer App To Fake Your GPS Location On Android
- Part 4: Other FAQs about Changing Location on Android
- Полный список
- Прочее
Android Turn on GPS programmatically
Jan 2, 2019 · 3 min read
In our previous article, we have taught you how to get location using FusedLocationProviderClient and we also mentioned in that article that for using this feature, you need to turn on device GPS manually by redirecting to settings of your device.
Programmatically we can turn on GPS in two ways. First, redirect the user to location settings of a device (by code) or another way is to ask to turn on GPS by GPS dialog using LocationSettingsRequest and SettingsClient.
First method:
By usin g this, the user will be redirected to the Settings page of your device and user has to turn on GPS manually.
Second method:
In this method, we will show you code to turn on GPS using android gms location request and setting clients. Here we provide a custom class GpsUtils.java with a code written in it with method turnGPSOn(). The method has a callback listener to check the current status of GPS. If GPS is already turned on, no further code will be determined and callback revert true as GPS is on. Let’s look at the code below and we will show how to use GpsUtils.java.
SettingsClient class is the main key point for interacting with location-based API. This API makes it easy for an app to ensure that the device’s system settings are properly configured for the app’s location needs.
LocationSettingsRequest Specifies the types of location services the client is interested in using. Settings will be checked for optimal functionality of all requested services. Use LocationSettingsRequest.Builder to construct this object.
GPS Dialog will be shown for SettingsClient’s failure callback and it will result in an activity’s onActivityResult(). So basically if the user agrees for turn on GPS, we can enable GPS flag in our activity.
and now call GpsUtils class before getting a location.
We recommend you to put this code in onCreate() of your activity. So that, turn on GPS and getting a location works well one by one. And also GPS takes some minor delay to trace your device location.
We have provided code in the previous article to get a location. Thus, we made changes for GPS in that code and republish the same code.
Find code here. Code contains previous article example for getting the current location.
Источник
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.
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.
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.
Источник
Полный список
— получаем данные о местоположении
Android устройства могут предоставить нам данные по нашему текущему местоположению. Это, конечно, очень удобно и вовсю используется для, например, пользования картой, получения актуальной для вашей местности информации (прогноз погоды), всевозможных чекинов и пр.
Реализация этого всего вполне проста. Мы вешаем слушателя на провайдера и получаем данные. На данный момент есть два провайдера: GPS и Network.
GPS – тут все понятно, это данные с GPS-спутников.
Network – это координаты, которые можно получить через сотовую связь или WiFi. Для этого провайдера нужен инет.
Напишем простое приложение, которое будет запрашивать и отображать координаты.
Project name: P1381_Location
Build Target: Android 2.3.3
Application name: Location
Package name: ru.startandroid.develop.p1381location
Create Activity: MainActivity
В strings.xml добавим строки:
Несколько TextView, в которые мы будем выводить данные, и кнопка для открытия настроек местоположения.
В onCreate определяем TextView-компоненты и получаем LocationManager, через который и будем работать.
В onResume вешаем слушателя с помощью метода requestLocationUpdates. На вход передаем:
— тип провайдера: GPS_PROVIDER или NETWORK_PROVIDER
— минимальное время (в миллисекундах) между получением данных. Я укажу здесь 10 секунд, мне этого вполне хватит. Если хотите получать координаты без задержек – передавайте 0. Но учитывайте, что это только минимальное время. Реальное ожидание может быть дольше.
— минимальное расстояние (в метрах). Т.е. если ваше местоположение изменилось на указанное кол-во метров, то вам придут новые координаты.
— слушатель, объект locationListener, который рассмотрим ниже
Также здесь обновляем на экране инфу о включенности провайдеров.
В onPause отключаем слушателя методом removeUpdates.
locationListener – слушатель, реализует интерфейс LocationListener с методами:
onLocationChanged – новые данные о местоположении, объект Location. Здесь мы вызываем свой метод showLocation, который на экране отобразит данные о местоположении.
onProviderDisabled – указанный провайдер был отключен юзером. В этом методе вызываем свой метод checkEnabled, который на экране обновит текущие статусы провайдеров.
onProviderEnabled – указанный провайдер был включен юзером. Тут также вызываем checkEnabled. Далее методом getLastKnownLocation (он может вернуть null) запрашиваем последнее доступное местоположение от включенного провайдера и отображаем его. Оно может быть вполне актуальным, если вы до этого использовали какое-либо приложение с определением местоположения.
onStatusChanged – изменился статус указанного провайдера. В поле status могут быть значения OUT_OF_SERVICE (данные будут недоступны долгое время), TEMPORARILY_UNAVAILABLE (данные временно недоступны), AVAILABLE (все ок, данные доступны). В этом методе мы просто выводим новый статус на экран.
Провайдеры включаются и отключаются в настройках системы. Тем самым, просто определяется доступен ли провайдер для получения от него координат. Чуть позже увидим, как можно отправить юзера в эти настройки. Программное включение/выключение провайдеров через стандартные методы недоступно.
Далее идут свои методы.
showLocation на вход берет Location, определяет его провайдера методом getProvider и отображает координаты в соответствующем текстовом поле.
formatLocation на вход берет Location, читает из него данные и форматирует из них строку. Какие данные он берет: getLatitude – широта, getLongitude – долгота, getTime – время определения.
checkEnabled определяет включены или выключены провайдеры методом isProviderEnabled и отображает эту инфу на экране.
Метод onClickLocationSettings срабатывает по нажатию кнопки Location settings и открывает настройки, чтобы пользователь мог включить или выключить провайдер. Для этого используется Intent с action = ACTION_LOCATION_SOURCE_SETTINGS.
Осталось в манифесте прописать разрешение на определение координат — ACCESS_FINE_LOCATION, которое позволит нам использовать и Network и GPS. Также существует разрешение ACCESS_COARSE_LOCATION, но оно дает доступ только к Network-провайдеру.
С кодом все, давайте смотреть, что получилось. Все сохраняем и запускаем приложение.
У меня на планшете сейчас выключен GPS, выключен WiFi, вставлена симка и выключен мобильный интернет.
Запускаю приложение и вижу такую картину:
GPS выключен, Network включен. Но инета нет, поэтому Network мне ничего не дает. Надо включить либо мобильный инет, либо WiFi.
Я включаю WiFi. Проходит секунд 15-20 и инфа с Network пошла
Видим широту, долготу и время.
Напомню, что мы ставили минимальную скорость обновления – 10 сек. Но у меня провайдер Network выдает данные не чаще, чем раз в минуту.
Теперь давайте включим GPS. Для этого мы специально повесили кнопку Location settings, которую надо будет нажать пользователю, чтобы перейти в настройки. Жмем кнопку.
Видим, что GPS выключен, а Network включен. Наше приложение показывало все верно.
Разумеется, GPS можно включать и выключать через быстрые настройки системы (справа сверху). Но не все пользователи об этом знают. А тут мы их точно направим.
Включаем GPS и жмем Назад, чтобы вернуться в приложение.
GPS теперь показывает что он включен, ждем координаты. Для этого имеет смысл подойти к окну, больше вероятности, что поймаем сигнал.
В итоге сигнал пойман и получен результат.
У GPS через какое-то время включился статус 2 (AVAILABLE).
А у Network тишина со статусом. Не знаю, нормально это или нет.
Если с GPS сигналом все ок, то каждые 10 сек вы будете получать инфу о вашем местоположении. Если убрать планшет от окна, получим плохой сигнал: данные могут приходить реже и статус у меня иногда меняется на 1 (TEMPORARILY_UNAVAILABLE).
Прочее
Есть еще третий тип провайдера — PASSIVE_PROVIDER. Сам по себе этот провайдер никакие данные не вернет. Но повесив на него слушателя, вы сможете получать данные о местоположении, когда кто-то еще в системе пытается определить местоположение через обычные провайдеры. Система будет дублировать результаты и вам.
Метод getAllProviders вернет вам список всех доступных провайдеров. Метод getProviders(boolean enabledOnly) вернет либо все, либо только включенные.
Объект Location кроме координат, времени и провайдера имеет еще несколько атрибутов, которые могут прийти и пустыми:
getAccuracy – точность показания в метрах
getAltitude – высота над уровнем моря в метрах
getSpeed – скорость движения в м/с
getBearing – насколько я понял, это угол, на который текущая траектория движения отклоняется от траектории на север. Он же азимут.
Местоположение можно протестировать и через AVD эмулятор. Для этого надо в Eclipse открыть DDMS (Window > Open Perspective > DDMS) и выбрать вкладку Emulator Control. Внизу будет вкладка Manual, на которой есть поля для ввода координат и кнопка отправки.
На следующем уроке:
— создаем приложение с картой
— настраиваем карту и обрабатываем ее события
— программно меняем положение камеры
Присоединяйтесь к нам в Telegram:
— в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.
— в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Kotlin, RxJava, Dagger, Тестирование
— ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня
— новый чат Performance для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме
Источник