Get current location android kotlin

Get current location android kotlin

Handheld devices may track their geographic position, and they may interact with map services to graphically interfere with a user’s location needs.

The Android OS itself contains a location framework with classes in the package android.location . However, the official position of Google is to favor the Google Play Services Location API because it is more elaborate and simpler to use. We follow this suggestion and talk about the services API in the following paragraphs. Location is about finding out the geographical position of a device as a latitude-longitude pair.

You can find article for Java language here.

To make the Services Location API available to your app, add the following as dependencies in your app module’s build.gradle file

The easiest way to get the device’s position is to get the last known location. To do so, in your app request permissions, add the following:

GPS resolution with fewer than ten yards needs FINE location permission, while the coarser network-based resolution with approximately 100 yards needs the COARSE location permission. Adding both to the manifest file gives us the most options, but depending on your needs, you could continue with just the coarse one.

Then, inside you component (for example, inside onCreate() ), you construct a FusedLocationProviderClient as follows:

Wherever needed in your app, you can use it to get the last known location.

Here, checkPermission() checks and possibly acquires the needed permissions as described here. This could be, for example, the following:

The function checkPermission() , if necessary, tries to acquire permission from a system activity. Whether the user grants permissions, upon return from this activity, your app may accordingly react to the result.

If your app needs to track updates on changing locations, you follow a different approach. First, the permissions needed are the same as stated earlier for the last known location, so there’s no change there. The difference is in requesting periodic updates from the fused location provider. For that we need to define a location settings object. To create one, write the following:

The .apply construct lets us configure the object faster. For example, fastestInterval = 10000 internally gets translated to reqSetting.setFastestInterval(10000) . The meanings of the individual settings are as follows:

  • fastestInterval . The fastest possible total update interval in milliseconds for the location provider.
  • interval . The requested interval in milliseconds. This setting is only approximate.

priority . The requested accuracy. This setting influences the battery usage. This value will be internally adapted according to available permissions. The following are possible values (constants from LocationRequest ):

  • PRIORITY_NO_POWER . Fetches passive updates only if other requestors actively request updates
  • PRIORITY_LOW_POWER . Updates only on «city» levels
  • PRIORITY_BALANCED_POWER_ACCURACY . Updates only on «city street block» levels
  • PRIORITY_HIGH_ACCURACY . Uses the highest possible accuracy available

smallestDisplacement . This is the smallest displacement in meters necessary for an update message to be fired.

With that location request setting, we check whether the system is able to fulfill our request. This happens in the following code snippet:

This asynchronously performs a check. If high accuracy is requested and the device’s setting won’t allow updates based on GPS data, the corresponding system settings dialog gets called. The latter happens somewhat awkwardly inside the exception catch. The result of the corresponding system intent call ends up in the following:

With all set up correctly and enough permissions, we now can register for location updates via the following:

To stop location updates, you move locationUpdates to a class field and react to stop requests via the following:

Источник

Getting Current Location in Kotlin

Dec 13, 2017 · 5 min read

Getting Location using Fused Location Provider

  • It provides simple and easy to use APIs.
  • Provides high accuracy over other options.
  • Utilizes low power by choosing the most efficient way to access the location.

With respect to fused location provider, we can broadly classify the API usage in three use cases.

  1. getLastLocation(GoogleApiClient) this API should be used when there is no need for continuous access to location from an application. Like one shot access or get user location based on some action. This is the simplified way to get the device location and also may not provide high accuracy.
  2. requestLocationUpdates(GoogleApiClient,LocationRequest, LocationListener) this API should be used when there a need for continuous location updates and the location is accessed when the application is active in foreground.
  3. requestLocationUpdates (GoogleApiClient, LocationRequest, PendingIntent) this API is used to receive location updates in the background even when the application is not active. So the difference is PendingIntent.

1 Add neccesary Permissions in AndroidManifest.xml

2 To use the location manager make the Google play service available via your app build.gradle file.

3 We have to give location runtime permission also

/** * Return the current state of the permissions needed. */

4 Now you can access the last known location. The fuse location provider provides a new simple API.

Источник

Getting Current Location on Android Using Kotlin

by Dody Prasetya · June 14, 2020

Have you ever wonder how to get a current location on Android programmatically? Hmm, the answer is so easy. You need to know how to use the fused location provider. Basically, it will give you the last known location which can be used as the current location.

What will the app look like?

The app will look like this after you finish this tutorial:

What will you learn?

  • Know how to use the FusedLocationProviderClient to access the last location data.
  • Opening the Google Maps app using the current location data.

Note: In this post, I used Android Studio 4.0, make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.72.

Getting Started – Getting Current Location on Android

Open your Android Studio and choose to Start a new Android Studio Project. Then set the Application Name CurrentLocationApp and select Kotlin as the language. Give the Activity Name MainActivity and wait until the Android Studio finishes preparing your project.

First, set up the app/build.gradle file and add this inside the dependencies block code:

After that, sync the project and proceed to the next step.

Preparing the XML Layout

The first is preparing the XML layout for our app here. Open the activity_main.xml inside the res/layout directory and put the code below:

This layout only contains TextView to show latitude and longitude data and also Buttons to get the current location and open the Google map application. The app will look like this if you run the app:

Write some codes

Open the MainActivity.kt file and write this code:

First, we need to initialize the FusedLocationProviderClient in order to access the current location data on Android. Just write the code adobe and it is very easy.

Next, create a new method getCurrentLocation() that we will implement the getLastLocation() function.

On Kotlin, you access the location data using the lastLocation provided by FusedLocationProviderClient and it will return the location data such as latitude, longitude, provider, etc. using the fused location provider requires you to grant the location permission. The permission that will be used is ACCESS_FINE_LOCATION.

Open the AndroidManifest.xml file and add the permission:

After that, back to MainActivity.kt file and add another method onRequestPermissionsResult() to handle permission callback and the openMap() method to implement the open on Google Map app.

Try to run the app and it will look like this:

Don’t forget to allow the permission request to get the current location.

The final code of the MainActivity.kt will be like this:

Where to go next?

You can download this full code from the link below:

Be sure to check my other cool posts here about:

I hope you like my post, comment, and share it with love!

Источник

Current Location Android Kotlin With Latitude Longitude Programmatically

It is necessary to find C urrent Location Android Kotlin latitude longitude programmatically when you are developing location-based applications.

For example, when finding restaurants near by you, you need your current location, latitude and longitude.

In C urrent Location Android Kotlin example tutorial, you will learn to get current latitude and longitude of Android device.

We will use Google’s FusedLocationAPI for getting current location latitude longitude.

Following is the output of C urrent Location Android Kotlin example tutorial programmatically:

Download Source Code For Current Location Android Kotlin Example

Step 1. New Project

Create a new project in Android Studio. Select your first activity as empty activity.

Step 2. Updating build.gradle(Module:app)

In build.gradle(Module:app) file add this:

Above lines will add necessary classes for integrating various google services like GPS, push notification , google map etc.

Step 3. Interfaces

Implement required interfaces

Step 4. Required instances

Step 5. Updating onCreate()

Put following in onCreate() function:

Step 6. Overriding methods

Override necessary methods.

Step 7. Adding permissions

Last but not least, put required permissions in AndroidManifest.xml:

If you are targeting marshmallow and after versions (targetSdkVersion >=23) then you have to check for run-time permissions.

Now full source code:

AndroidManifest.xml

build.gradle(Module:app)

Step 7. Full Source code for MainActivity.

activity_main.xml

MainActivity.kt

In above class, there is a method

This method is used to check whether location service is on or off in your phone. If off, then it will pop up one dialog, which will take the user to settings to enable location service.

After following all the steps, you should be able get current location in terms of latitude and longitude with kotlin source code.

Источник

Getting Current Location in Android using Kotlin

Getting Current Location in Android using Kotlin 2

So in this tutorial, we’ll be learning about getting the user’s current location in Android using kotlin (latitude & longitude).

We will be using Fused Location Provider.

The fused location provider retrieves the device’s last known location. The fused location provider is one of the location APIs in Google Play services.

It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power.

STEP – 1

Add dependency in build.gradle file of you app.

STEP – 2

Ask for Location permission from User. Since Location is a dangerous Permission for android so we need to ask the user to grant permission for it.

Android offers two location permissions:

  1. ACCESS_COARSE_LOCATION
  2. ACCESS_FINE_LOCATION.

The permission you choose determines the accuracy of the location returned by the API.

Add these two permission in you manifest file.

STEP – 3

As you may know that from Android 6.0 (Marshmallow) you must request permissions for important access in the runtime. Cause it’s a security issue where while installing an application, the user may not clearly understand about important permission of their device.

As we need the location information of the user so we’ll need to implement the permission request also in runtime.

These will be in further Steps

PART – 1

checkPermissions()

This method will tell us whether or not the user grant us to access ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.

PART – 2

onRequestPermissionsResult()

This method is called when a user Allow or Deny our requested permissions. So it will help us to move forward if the permissions are granted.

PART – 3

isLocationEnabled()

This will check if the user has turned on location from the setting, Cause user may grant the app to user location but if the location setting is off then it’ll be of no use.

You may notice that while requesting for permission and in after the permission result, we used PERMISSION_ID, it’s a interger value which helps us to identify user’s action with which permission request. You can provide any unique value here.

STEP – 4

Now time to write the MainActivity.kt

STEP – 6

Now we’ll use the actual Fused Location Provider API to get the user’s current position. For this, you should declare a variable first lateint var using mFusedLocationClient: FusedLocationClient

Then we’ll create a method named getLastLocation() which will use to API and return the last recorder location information of the device. Also this method will check first if our permission is granted or not and if the location setting is turned on.

As you can see first it’ll check if we have granted permissions or not using our created method checkPermission() and if not, it’ll request for location permission. Then it’ll check if the location setting is turned on or off. If turned off, will open the location setting using intent to turn it on.

If every requirment is good then it’ll look for the last recorded location information and put the latitude and longitude values in our TextView using

STEP – 7

STEP – 8 (optional)

But here’s a thing you must know, for some rare cases the location can be null like:

  • In some device, if you turn off the location and again turn on, the previous recorded location information will be cleared.
  • May the user never turned on location before using your App, this time previous location information will be null too.

To avoid these rare cases when the location == null, we called a new method requestNewLocation() which will record the location information in runtime.

This method will make a new location request with highest accuracy.

When an update receives it’ll call a callBack method named mLocationCallback.

So when we get the location update, we set the latitude and longitude values in our TextViews.

So finally we’ll call our getLastLocation() method in our onCreate() method and also when user grants the permission request.

Источник

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