2012-03-29 14 views
10

Estoy desarrollando una aplicación para Android que necesita activar el GPS.Cómo activar el GPS en Android

He leído un montón de temas en un montón de foros y la respuesta que he encontrado es:

que no es posible

... Pero la "Cerberus" aplicación convierte mi GPS encendido ... entonces ... ¡es posible!

¿Alguien me puede ayudar con esto?

+0

Aquí está el código- [½ vuelta n o fuera de GPS mediante programación] [1] [1]:. http://stackoverflow.com/questions/4721449/enable-gps-programatically-like-tasker – Rajkiran

+0

trabajo sólo en androide <2.3.3 –

Respuesta

14

No es imposible, e inapropiado. No puedes simplemente administrar el teléfono del usuario sin su autoridad.

Desde la reproducción de la tienda:

"Cerberus habilita automáticamente GPS si está apagado cuando intenta localizar su dispositivo (sólo en Android 2.3.3 <) y puede protegerlo de la desinstalación no autorizada - más información en la configuración de la aplicación ".

Usted puede hacer algo como esto:

startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
+1

OK ... todos los dispositivos que utilizo son 2.3.3 + ... así que ... gracias por la respuesta ... –

+1

@goodm: FYI, no es imposible. Pero sí, es inapropiado. – Rajkiran

+3

¿Cómo están funcionando los olaCabs? En un solo mensaje, están habilitando el gps sin enviar al usuario a la configuración de GPS panal. – Alpesh

11

Solía ​​haber un exploit que permitía encender el GPS mediante una aplicación sin permisos especiales. Ese exploit ya no existe a partir de 2.3 (en la mayoría de ROM). Aquí hay otro post que habla de ello,

How can I enable or disable the GPS programmatically on Android?

"GPS activado" es un entorno seguro, por lo que debe tener el permiso WRITE_SECURE_SETTINGS. Sin embargo, este es un permiso de firma protegido, por lo que su aplicación no recibirá esta autorización a menos que esté firmado con el certificado de la plataforma del fabricante.

Lo correcto es enviar al usuario a la página de configuración de ubicación y permitirle habilitar el GPS si lo desea. por ejemplo,

Intent i = new 
Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
startActivity(i); 
1

es posible que desee echa un vistazo a este hilo

How can I enable or disable the GPS programmatically on Android?

aquí están los códigos copiados de ese hilo

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); 


    } 
} 

pero la solución no es recomendable ya que no estará disponible Le a la versión androide> 2.3 supposingly .. do comprobar los comentarios

5
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setMessage(R.string.gps_disabled_message) 
     .setCancelable(false) 
     .setPositiveButton("Yes", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        startActivity(intent);     
      } 
     }) 
     .setNegativeButton("No", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       dialog.cancel(); 
      } 
     }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 

Esto crea una alerta y permite al usuario ir a la pantalla de configuración y pulsa el botón de nuevo a venir a la derecha de nuevo a su aplicación. El exploit del widget de poder no funciona más allá de 2.3, que yo sepa.

2

Usar este código // turnGPSON llamada Después setContentView (XML)

private void turnGPSOn() { 

    String provider = android.provider.Settings.Secure.getString(
      getContentResolver(), 
      android.provider.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); 
    } 
}** 
0

Creo que tenemos más mejor versión para permitir la ubicación sin necesidad de abrir la configuración de mapa al igual que funciona Google.

Será parece a esto -

enter image description here

Agregar dependencia en Gradle - compilación 'com.google.android.gms: play-servicios de localización: 10.0.1'

public class MapActivity extends AppCompatActivity { 

    protected static final String TAG = "LocationOnOff"; 


    private GoogleApiClient googleApiClient; 
    final static int REQUEST_LOCATION = 199; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

     this.setFinishOnTouchOutside(true); 

     // Todo Location Already on ... start 
     final LocationManager manager = (LocationManager) MapActivity.this.getSystemService(Context.LOCATION_SERVICE); 
     if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapActivity.this)) { 
      Toast.makeText(MapActivity.this,"Gps already enabled",Toast.LENGTH_SHORT).show(); 
      finish(); 
     } 
     // Todo Location Already on ... end 

     if(!hasGPSDevice(MapActivity.this)){ 
      Toast.makeText(MapActivity.this,"Gps not Supported",Toast.LENGTH_SHORT).show(); 
     } 

     if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(MapActivity.this)) { 
      Log.e("TAG","Gps already enabled"); 
      Toast.makeText(MapActivity.this,"Gps not enabled",Toast.LENGTH_SHORT).show(); 
      enableLoc(); 
     }else{ 
      Log.e("TAG","Gps already enabled"); 
      Toast.makeText(MapActivity.this,"Gps already enabled",Toast.LENGTH_SHORT).show(); 
     } 
    } 


    private boolean hasGPSDevice(Context context) { 
     final LocationManager mgr = (LocationManager) context 
       .getSystemService(Context.LOCATION_SERVICE); 
     if (mgr == null) 
      return false; 
     final List<String> providers = mgr.getAllProviders(); 
     if (providers == null) 
      return false; 
     return providers.contains(LocationManager.GPS_PROVIDER); 
    } 

    private void enableLoc() { 

     if (googleApiClient == null) { 
      googleApiClient = new GoogleApiClient.Builder(MapActivity.this) 
        .addApi(LocationServices.API) 
        .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() { 
         @Override 
         public void onConnected(Bundle bundle) { 

         } 

         @Override 
         public void onConnectionSuspended(int i) { 
          googleApiClient.connect(); 
         } 
        }) 
        .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() { 
         @Override 
         public void onConnectionFailed(ConnectionResult connectionResult) { 

          Log.d("Location error","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(MapActivity.this, REQUEST_LOCATION); 

           finish(); 
          } catch (IntentSender.SendIntentException e) { 
           // Ignore the error. 
          } 
          break; 
        } 
       } 
      }); 
     } 
    } 

} 
0
public class NearestActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener { 
    private Location mylocation; 
    private GoogleApiClient googleApiClient; 
    private final static int REQUEST_CHECK_SETTINGS_GPS=0x1; 
    private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2; 
    public static double gpsLat, gpsLong; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     googleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this, 0, this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     mylocation = location; 
     if (mylocation != null) { 
      gpsLat = mylocation.getLatitude(); 
      gpsLong = mylocation.getLongitude(); 
      if(adapter.getItemCount()!=0) { 
       Collections.sort(list, new Comparator<TokoUpload>() { 
        @Override 
        public int compare(TokoUpload o1, TokoUpload o2) { 
         return o1.getMeter() - o2.getMeter(); 
        } 
       }); 
       adapter.notifyDataSetChanged(); 
      } 
     } 
    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     checkPermissions(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    private void getMyLocation(){ 
     if(googleApiClient != null) { 
      if (googleApiClient.isConnected()) { 
       int permissionLocation = ContextCompat.checkSelfPermission(NearestTokoActivity.this, 
         android.Manifest.permission.ACCESS_FINE_LOCATION); 
       if (permissionLocation == PackageManager.PERMISSION_GRANTED) { 
        mylocation =      LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 
        LocationRequest locationRequest = new LocationRequest(); 
        locationRequest.setInterval(3000); 
        locationRequest.setFastestInterval(3000); 
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder() 
          .addLocationRequest(locationRequest); 
        builder.setAlwaysShow(true); 
        LocationServices.FusedLocationApi 
          .requestLocationUpdates(googleApiClient, locationRequest, this); 
        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.SUCCESS: 
            int permissionLocation = ContextCompat 
              .checkSelfPermission(NearestTokoActivity.this, 
                android.Manifest.permission.ACCESS_FINE_LOCATION); 
            if (permissionLocation == PackageManager.PERMISSION_GRANTED) { 
             mylocation = LocationServices.FusedLocationApi 
               .getLastLocation(googleApiClient); 
            } 
            break; 
           case LocationSettingsStatusCodes.RESOLUTION_REQUIRED: 
            try { 
             status.startResolutionForResult(NearestTokoActivity.this, 
               REQUEST_CHECK_SETTINGS_GPS); 
            } catch (IntentSender.SendIntentException ignored) { 
            } 
            break; 
           case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE: 
            break; 
          } 
         } 
        }); 
       } 
      } 
     } 
    } 

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     switch (requestCode) { 
      case REQUEST_CHECK_SETTINGS_GPS: 
       switch (resultCode) { 
        case Activity.RESULT_OK: 
         getMyLocation(); 
         break; 
        case Activity.RESULT_CANCELED: 
         finish(); 
         break; 
       } 
       break; 
     } 
    } 

    private void checkPermissions(){ 
     int permissionLocation = ContextCompat.checkSelfPermission(NearestTokoActivity.this, 
       android.Manifest.permission.ACCESS_FINE_LOCATION); 
     List<String> listPermissionsNeeded = new ArrayList<>(); 
     if (permissionLocation != PackageManager.PERMISSION_GRANTED) { 
      listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION); 
      if (!listPermissionsNeeded.isEmpty()) { 
       ActivityCompat.requestPermissions(this, 
         listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS); 
      } 
     }else{ 
      getMyLocation(); 
     } 

    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     int permissionLocation = ContextCompat.checkSelfPermission(NearestTokoActivity.this, 
       android.Manifest.permission.ACCESS_FINE_LOCATION); 
     if (permissionLocation == PackageManager.PERMISSION_GRANTED) { 
      getMyLocation(); 
     } 
    } 
} 
Cuestiones relacionadas