Building Location Based Based Application , Getting location data for your app based on combined signals from the device sensors using a battery-efficient API , The location APIs available in Google Play services facilitate adding location awareness to your app with automated location tracking.
The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs. fused location provider API is Simple, battery-efficient location API for Android .
1. Gradle
file : build.gradle(App Level)
dependencies { implementation "com.google.android.gms:play-services-location:18.0.0" }
2. AndroidManifest
file : AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tutorialsbuzz.mylocation"> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> .......... .......... .......... </manifest>
3. XML Layout
Create XML Layout and Add TextView and Button to it .
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:textSize="22sp" /> <Button android:id="@+id/fetchMyLocation" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:text="Fetch My Location" android:textSize="20sp" /> </LinearLayout>
4. Activity
- Create MainActivity class which extends AppCompatActivity and inside onCreate function set the content of Activity with Above define XML Layout .
- On Button click call fetch Current Location Details .
- Before Getting Location Details using FusedLocation API , Request for App Location permission once the permission is granted update UI with Latitude and Longitude .
Get Last Known Location
- Create an instance of the Fused Location Provider Client.
- Once you have created the Location Services client you can get the last known location of a user's device. When your app is connected to these you can use the fused location provider's getLastLocation() method to retrieve the device location.
mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task -> val location: Location? = task.result if (location == null) { // Create Location Request } else { // Update Ui // Lat Lng ( location.latitude, location.longitude ) } }
Making Location Request .
If the returned location is null then make another location request update on locationProvider Client , requestLocationUpdates function takes locationRequest and a Callback (Receives Location) .
The following code snippet illustrates the request and callBack on Update :
// 1. Create Location Request val locationRequest = LocationRequest.create().apply { interval = 10000 fastestInterval = 5000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } // 2. Request for location update mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) mFusedLocationClient.requestLocationUpdates( locationRequest, mLocationCallback, Looper.myLooper() ) //3. CallBack for location update Request mLocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { // Update UI With Lat Lng // locationResult.lastLocation.latitude // locationResult.lastLocation.longitude } }
file : MainActivity.kt
package com.tutorialsbuzz.mylocation class MainActivity : AppCompatActivity() { private lateinit var mFusedLocationClient: FusedLocationProviderClient private lateinit var mLocationCallback: LocationCallback val PERMISSION_ID = 42 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) fetchMyLocation.setOnClickListener({ getMyCurrenLocation() }) //CallBack for location update Request mLocationCallback = object : LocationCallback() { override fun onLocationResult(locationResult: LocationResult) { // Update UI With Lat Lng updateUIWithLatLng( locationResult.lastLocation.latitude, locationResult.lastLocation.longitude ) } } } fun updateUIWithLatLng(latitude: Double, longitude: Double) { val textLabel = " Latitude: $latitude \n Longitude: $longitude " textView.text = textLabel } fun requestPermissions() { ActivityCompat.requestPermissions( this, arrayOf( Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION ), PERMISSION_ID ) } fun getMyCurrenLocation() { if (ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( this, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED ) { //request for location permission requestPermissions() } else { mFusedLocationClient.lastLocation.addOnCompleteListener(this) { task -> val location: Location? = task.result if (location == null) { // Create Location Request val locationRequest = LocationRequest.create().apply { interval = 10000 fastestInterval = 5000 priority = LocationRequest.PRIORITY_HIGH_ACCURACY } // Request for location update mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this) mFusedLocationClient.requestLocationUpdates( locationRequest, mLocationCallback, Looper.myLooper() ) } else { // Update Ui With Lat Lng updateUIWithLatLng(location.latitude, location.longitude) } } } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == PERMISSION_ID) { if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) { //Permission Granted getMyCurrenLocation() showToast("Permission Granted:") } else { // Permission Denied showToast("Permission Denied:") } } } fun showToast(msg: String) { Toast.makeText(this@MainActivity, msg, Toast.LENGTH_LONG).show() } }
No comments:
Post a Comment