Setting home location android

Android — Location Based Services

Android location APIs make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology.

This becomes possible with the help of Google Play services, which facilitates adding location awareness to your app with automated location tracking, geofencing, and activity recognition.

This tutorial shows you how to use Location Services in your APP to get the current location, get periodic location updates, look up addresses etc.

The Location Object

The Location object represents a geographic location which can consist of a latitude, longitude, time stamp, and other information such as bearing, altitude and velocity. There are following important methods which you can use with Location object to get location specific information −

float distanceTo(Location dest)

Returns the approximate distance in meters between this location and the given location.

Get the estimated accuracy of this location, in meters.

Get the altitude if available, in meters above sea level.

Get the bearing, in degrees.

Get the latitude, in degrees.

Get the longitude, in degrees.

Get the speed if it is available, in meters/second over ground.

True if this location has an accuracy.

True if this location has an altitude.

True if this location has a bearing.

True if this location has a speed.

Clears the contents of the location.

void setAccuracy(float accuracy)

Set the estimated accuracy of this location, meters.

void setAltitude(double altitude)

Set the altitude, in meters above sea level.

void setBearing(float bearing)

Set the bearing, in degrees.

void setLatitude(double latitude)

Set the latitude, in degrees.

void setLongitude(double longitude)

Set the longitude, in degrees.

void setSpeed(float speed)

Set the speed, in meters/second over ground.

Returns a string containing a concise, human-readable description of this object.

Get the Current Location

To get the current location, create a location client which is LocationClient object, connect it to Location Services using connect() method, and then call its getLastLocation() method. This method returns the most recent location in the form of Location object that contains latitude and longitude coordinates and other information as explained above. To have location based functionality in your activity, you will have to implement two interfaces −

These interfaces provide following important callback methods, which you need to implement in your activity class −

Sr.No. Method & Description
1

abstract void onConnected(Bundle connectionHint)

This callback method is called when location service is connected to the location client successfully. You will use connect() method to connect to the location client.

abstract void onDisconnected()

This callback method is called when the client is disconnected. You will use disconnect() method to disconnect from the location client.

abstract void onConnectionFailed(ConnectionResult result)

This callback method is called when there was an error connecting the client to the service.

You should create the location client in onCreate() method of your activity class, then connect it in onStart(), so that Location Services maintains the current location while your activity is fully visible. You should disconnect the client in onStop() method, so that when your app is not visible, Location Services is not maintaining the current location. This helps in saving battery power up-to a large extent.

Get the Updated Location

If you are willing to have location updates, then apart from above mentioned interfaces, you will need to implement LocationListener interface as well. This interface provide following callback method, which you need to implement in your activity class −

Sr.No. Callback Methods & Description
1

abstract void onLocationChanged(Location location)

This callback method is used for receiving notifications from the LocationClient when the location has changed.

Location Quality of Service

The LocationRequest object is used to request a quality of service (QoS) for location updates from the LocationClient. There are following useful setter methods which you can use to handle QoS. There are equivalent getter methods available which you can check in Android official documentation.

Sr.No. Callback Method & Description
1

Set the duration of this request, in milliseconds.

Set the request expiration time, in millisecond since boot.

Explicitly set the fastest interval for location updates, in milliseconds.

Set the desired interval for active location updates, in milliseconds.

Set the number of location updates.

Set the priority of the request.

Now for example, if your application wants high accuracy location it should create a location request with setPriority(int) set to PRIORITY_HIGH_ACCURACY and setInterval(long) to 5 seconds. You can also use bigger interval and/or other priorities like PRIORITY_LOW_POWER for to request «city» level accuracy or PRIORITY_BALANCED_POWER_ACCURACY for «block» level accuracy.

Activities should strongly consider removing all location request when entering the background (for example at onPause()), or at least swap the request to a larger interval and lower quality to save power consumption.

Displaying a Location Address

Once you have Location object, you can use Geocoder.getFromLocation() method to get an address for a given latitude and longitude. This method is synchronous, and may take a long time to do its work, so you should call the method from the doInBackground() method of an AsyncTask class.

The AsyncTask must be subclassed to be used and the subclass will override doInBackground(Params. ) method to perform a task in the background and onPostExecute(Result) method is invoked on the UI thread after the background computation finishes and at the time to display the result. There is one more important method available in AyncTask which is execute(Params. params), this method executes the task with the specified parameters.

Example

Following example shows you in practical how to to use Location Services in your app to get the current location and its equivalent addresses etc.

To experiment with this example, you will need actual Mobile device equipped with latest Android OS, otherwise you will have to struggle with emulator which may not work.

Create Android Application

Sr.No. Method & Description
1
Step Description
1 You will use Android studio IDE to create an Android application and name it as Tutorialspoint under a package com.example.tutorialspoint7.myapplication.
2 add src/GPSTracker.java file and add required code.
3 Modify src/MainActivity.java file and add required code as shown below to take care of getting current location and its equivalent address.
4 Modify layout XML file res/layout/activity_main.xml to add all GUI components which include three buttons and two text views to show location/address.
5 Modify res/values/strings.xml to define required constant values
6 Modify AndroidManifest.xml as shown below
7 Run the application to launch Android emulator and verify the result of the changes done in the application.

Following is the content of the modified main activity file MainActivity.java.

Following is the content of the modified main activity file GPSTracker.java.

Following will be the content of res/layout/activity_main.xml file −

Following will be the content of res/values/strings.xml to define two new constants −

Following is the default content of AndroidManifest.xml

Let’s try to run your Tutorialspoint application. I assume that, you have connected your actual Android Mobile device with your computer. To run the app from Android Studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, Android studio installer will display following window to select an option where you want to run your Android application.

Now to see location select Get Location Button which will display location information as follows −

Источник

Полный список

— получаем данные о местоположении

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 для обсуждения проблем производительности и для ваших пожеланий по содержанию курса по этой теме

Источник

Читайте также:  Что будет если прошить android
Оцените статью