Join FlipAndroid.COM Telegram Group: https://t.me/joinchat/F_aqThGkhwcLzmI49vKAiw


Activar GPS de forma programática como la aplicación Android de Ola Cabs

Estoy trabajando en una aplicación y la necesidad de integrar la ubicación GPS. Quiero cambiar el GPS por programa. La condición es: No quiero enviar al usuario al panel Configuración para habilitarlo. Quiero habilitarlo con fuerza o un solo mensaje funcionará (similar a la aplicación Android de Ola Cabs). Muchas preguntas son para esto en este sitio, pero todo el mundo está buscando la funcionalidad similar como la aplicación Ola Cabs. Así que he comenzado este hilo para que pueda ser claro para todos nosotros.

  • Cómo habilitar el acceso a la ubicación mediante programación en android?
  • 6 Solutions collect form web for “Activar GPS de forma programática como la aplicación Android de Ola Cabs”

    Compruebe el código abajo. En primer lugar, comprobará si la ubicación está habilitada o no y solicitará al usuario que active la ubicación.

    private GoogleApiClient googleApiClient; final static int REQUEST_LOCATION = 199; // check whether gps is enabled public boolean noLocation() { final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { // buildAlertMessageNoGps(); enableLoc(); return true; } return false; } private void enableLoc() { if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { @Override public void onConnectionFailed(ConnectionResult connectionResult) { Timber.v("Location error " + connectionResult.getErrorCode()); } }).build(); googleApiClient.connect(); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult( (Activity) context, REQUEST_LOCATION); } catch (IntentSender.SendIntentException e) { // Ignore the error. } break; } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_LOCATION: switch (resultCode) { case Activity.RESULT_CANCELED: { // The user was asked to change settings, but chose not to finish(); break; } default: { break; } } break; } } } 

    Aquí está mi código de trabajo 100% primero agrega esta compile 'com.google.android.gms:play-services:9.2.1' dependencia compile 'com.google.android.gms:play-services:9.2.1' a tu build.gradle (Module: app)

    Después de crear la clase con nombre StartLocationAlert.java y copiar este código y pegar en este archivo

     import android.app.Activity; import android.content.IntentSender; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.widget.Toast; import com.example.googlemappromt.MainActivity; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; import com.google.android.gms.vision.barcode.Barcode; /** * Created by Anirudh on 20/07/16. */ public class StartLocationAlert implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener { Activity context; protected static final int REQUEST_CHECK_SETTINGS = 0x1; GoogleApiClient googleApiClient; public StartLocationAlert(Activity context) { this.context = context; googleApiClient = getInstance(); if(googleApiClient != null){ //googleApiClient.connect(); settingsrequest(); googleApiClient.connect(); } } public GoogleApiClient getInstance(){ GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build(); return mGoogleApiClient; } public void settingsrequest() { Log.e("settingsrequest","Comes"); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() .addLocationRequest(locationRequest); builder.setAlwaysShow(true); //this is the key ingredient PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: // All location settings are satisfied. The client can initialize location // requests here. // Log.e("Application","Button Clicked"); break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: // Location settings are not satisfied. But could be fixed by showing the user // a dialog. // Log.e("Application","Button Clicked1"); try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). status.startResolutionForResult(context, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) { // Ignore the error. Log.e("Applicationsett",e.toString()); } break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: // Location settings are not satisfied. However, we have no way to fix the // settings so we won't show the dialog. //Log.e("Application","Button Clicked2"); Toast.makeText(context, "Location is Enabled", Toast.LENGTH_SHORT).show(); break; } } }); } @Override public void onConnected(@Nullable Bundle bundle) { /* MainActivity mm = new MainActivity(); mm.requestLocationUpdates();*/ Toast.makeText(context , "Connected", Toast.LENGTH_SHORT).show(); } @Override public void onConnectionSuspended(int i) { } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { } } 

    El uso de esta clase anterior se muestra a continuación

      @Override protected void onResume() { super.onResume(); Activity mContext = MainActivity.this //change this your activity name StartLocationAlert startLocationAlert = new StartLocationAlert(mContext); requestLocationUpdates(); } 

    Y no olvide agregar los permisos a continuación en el archivo AndroidManifest.xml o bien esto podría no funcionar correctamente

      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

    Espero que esto pueda ayudarte.

    He creado una biblioteca basada en la respuesta de Anirudh.

    Guía breve de cómo usarlo:

    1. Añadir a usted archivo build.gradle:

      Compilar 'net.alexandroid.utils: gps: 1.6'

    2. Implementar la interfaz GpsStatusDetectorCallBack.

    3. Implementar métodos de interfaz : onGpsSettingStatus y onGpsAlertCanceledByUser

    4. Crear variable de instancia:

      Private GpsStatusDetector mGpsStatusDetector;

    5. Instánciela en onCreate ():

      MGpsStatusDetector = nuevo GpsStatusDetector (este);

    6. En el lugar que usted necesita para comprobar el estado y mostrar un diálogo si es necesario añadir : mGpsStatusDetector.checkLocationSettingStatus ();

    7. Anular onActivityResult y añadir allí:

      MGpsStatusDetector.checkOnActivityResult (requestCode, resultCode);


    Más información sobre la biblioteca: https://github.com/Pulimet/GpsDetector-Library


    Ejemplo:

     public class MainActivity extends AppCompatActivity implements GpsStatusDetector.GpsStatusDetectorCallBack { private GpsStatusDetector mGpsStatusDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGpsStatusDetector = new GpsStatusDetector(this); mGpsStatusDetector.checkLocationSettingStatus(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); mGpsStatusDetector.checkOnActivityResult(requestCode, resultCode); } @Override public void onGpsSettingStatus(boolean enabled) { Log.d("TAG", "onGpsSettingStatus: " + enabled); } @Override public void onGpsAlertCanceledByUser() { Log.d("TAG", "onGpsAlertCanceledByUser"); } } 

    Aquí tengo el usuario de este código

     private void turnGPSOn(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.contains("gps")){ //if gps is disabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } private void turnGPSOff(){ String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(provider.contains("gps")){ //if gps is enabled final Intent poke = new Intent(); poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); poke.addCategory(Intent.CATEGORY_ALTERNATIVE); poke.setData(Uri.parse("3")); sendBroadcast(poke); } } 

    Permisos en el archivo de manifiesto:

     <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 

    Ola Cabs utiliza la API de configuración recién liberada para lograr esta funcionalidad. Según la nueva API, el usuario no necesita navegar a la página de configuración para habilitar los servicios de ubicación, lo que proporciona una integración transparente para el mismo. Por favor, lea a continuación para más detalles:

    https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi

     package com.example.user.myGPS; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.IntentSender; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.LocationSettingsRequest; import com.google.android.gms.location.LocationSettingsResult; import com.google.android.gms.location.LocationSettingsStates; import com.google.android.gms.location.LocationSettingsStatusCodes; public class MainActivity extends AppCompatActivity { private GoogleApiClient googleApiClient; final int REQUEST_CHECK_SETTINGS = 0x1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //-------Code to turn on GPS------------------ if (googleApiClient == null) { googleApiClient = new GoogleApiClient.Builder(MainActivity.this) .addApi(LocationServices.API).build(); googleApiClient.connect(); LocationRequest locationRequest = LocationRequest.create(); locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); locationRequest.setInterval(30 * 1000); locationRequest.setFastestInterval(5 * 1000); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest); builder.setAlwaysShow(true); builder.setNeedBle(true); PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build()); result.setResultCallback(new ResultCallback<LocationSettingsResult>() { @Override public void onResult(LocationSettingsResult result) { final com.google.android.gms.common.api.Status status = result.getStatus(); final LocationSettingsStates state = result.getLocationSettingsStates(); switch (status.getStatusCode()) { case LocationSettingsStatusCodes.SUCCESS: break; case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: try { status.startResolutionForResult(MainActivity.this,REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException e) {} break; case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: break; } } }); } } } 
    FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.