Android Request To Turn On GPS Pragmatically

In the previous tutorial we have seen  how to get location using FusedLocationProviderClient , for apps to request location the device needs to enable the appropriate system settings, such as GPS or Wi-Fi scanning . to turn on gps programmatically using android gms location request and setting clients by presenting the Location Settings dialog for the user to update their settings with a single tap.


1. Gradle


file : build.gradle
dependencies {

    implementation "com.google.android.gms:play-services-location:18.0.0"
}


2. XML Layout


file : activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="18sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

3. Set up a location request .

val locationRequest = LocationRequest.create().apply {
            interval = 10000
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

Create the location request and set the parameters as shown in this code sample:
  • Update interval : This method sets the rate in milliseconds at which your app prefers to receive location updates.
  • Fastest update interval : This method sets the fastest rate in milliseconds at which your app can handle location updates .
  • Priority : This method sets the priority of the request . It takes the following values 
1. PRIORITY_HIGH_ACCURACY 
2. PRIORITY_LOW_POWER 
3. PRIORITY_NO_POWER 

Prompt the user to change location settings


1.  Create a LocationSettingsRequest.Builder .

2.  Create SettingsClient instance .

3.  checkLocationSettings method of SettingsClient Checks if the relevant system settings are enabled on the device to  carry out the desired location requests.Call checkLocationSettings on settingsclient instance by passing locationSettingsRequest builder as parameter , it returns Task<LocationSettingsResponse> .
   
4.  Call addOnFailureListener and addOnFailureListener on Task .
  • Inside addOnSuccessListener All location settings are satisfied. The client can initialize locationrequests here.
  • Inside addOnFailureListener Location settings are not satisfied, but this can be fixed by showing the user a dialog. Show the dialog by calling startResolutionForResult() and check the result in onActivityResult().

3. Activity


MainActivity full code .

file : MainActivity.kt
package com.tutorialsbuzz.devicelocationsettings

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    override fun onResume() {
        super.onResume()
        requestDeviceLocationSettings();
    }

    // request device

    fun requestDeviceLocationSettings() {
        val locationRequest = LocationRequest.create().apply {
            interval = 10000
            fastestInterval = 5000
            priority = LocationRequest.PRIORITY_HIGH_ACCURACY
        }

        val builder = LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest)

        val client: SettingsClient = LocationServices.getSettingsClient(this)
        val task: Task<LocationSettingsResponse> = client.checkLocationSettings(builder.build())

        task.addOnSuccessListener { locationSettingsResponse ->
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            val state = locationSettingsResponse.locationSettingsStates

           val label =
	           "GPS >> (Present: ${state.isGpsPresent}  | Usable: ${state.isGpsUsable} ) \n\n" +
	           "Network >> ( Present: ${state.isNetworkLocationPresent} | Usable: ${state.isNetworkLocationUsable} ) \n\n" +
	           "Location >> ( Present: ${state.isLocationPresent} | Usable: ${state.isLocationUsable} )"

            showToast(label)

            textView.text = label

        }

        task.addOnFailureListener { exception ->
            if (exception is ResolvableApiException) {
                // Location settings are not satisfied, but this can be fixed
                // by showing the user a dialog.
                try {
                    // Show the dialog by calling startResolutionForResult(),
                    // and check the result in onActivityResult().
                    exception.startResolutionForResult(
                        this@MainActivity,
                        100
                    )
                } catch (sendEx: IntentSender.SendIntentException) {
                    // Ignore the error.
                    textView.text = sendEx.message.toString()
                }
            }
        }

    }

    fun showToast(msg: String) {
        Toast.makeText(this@MainActivity, msg, Toast.LENGTH_LONG).show()
    }
}




No comments:

Post a comment