2012-03-29 10 views
10

Pracuję nad aplikacją na Androida, która musi aktywować GPS.Jak włączyć GPS na Androidzie

Czytałem wiele tematów w wielu forach i odpowiedź znalazłem to:

nie jest możliwe

Ale ... „Cerberus” APP zamienia mój GPS na ... więc ... to jest możliwe!

Czy ktoś może mi w tym pomóc?

+0

Oto Code [o Skręć n lub odbiornik GPS, programowo] [1] [1]. http://stackoverflow.com/questions/4721449/enable-gps-programatically-like-tasker – Rajkiran

+0

praca tylko w android <2.3.3 –

Odpowiedz

14

Nie jest to niemożliwe i nieodpowiednie. Nie możesz po prostu zarządzać telefonem użytkownika bez jego uprawnień.

Od Sklepie Play:

„Cerberus automatycznie włącza GPS, jeśli jest wyłączony podczas próby zlokalizowania urządzenia (tylko na Androidzie < 2.3.3) można zabezpieczyć przed nieautoryzowanym usuwanie programów - więcej informacji w konfiguracji aplikacji. "

można zrobić coś takiego:

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

OK ... wszystkie urządzenia, których używam to 2.3.3 + ... więc ... dziękuję za odpowiedź ... –

+1

@goodm: FYI, to niemożliwe. Ale tak, to niewłaściwe. – Rajkiran

+3

W jaki sposób robią to olaCab? W jednym monicie aktywują gps, nie przesuwając użytkownika do panela ustawień GPS. – Alpesh

11

Nie było exploit, który pozwolił na włączenie GPS przez aplikację bez specjalnych uprawnień. Ta luka nie istnieje już od wersji 2.3 (w większości ROM-ów). Oto kolejny post, który mówi o tym,

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

„GPS włączony” to bezpieczna okolica, więc trzeba mieć pozwolenie WRITE_SECURE_SETTINGS. Jest to jednak pozwolenie na podpis, więc aplikacja nie zostanie przyznana, dopóki nie zostanie podpisana certyfikatem platformy producenta.

Prawidłowe jest wysłanie użytkownika na stronę ustawień lokalizacji i zezwolenie na włączenie GPS, jeśli chcą. np.

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

może chcesz sprawdzić ten wątek

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

Oto kody skopiowany z tego wątku

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


    } 
} 

ale rozwiązanie nie jest zalecane, ponieważ nie będzie dostępne le do wersji Android 2.3 supposingly> .. nie sprawdzić komentarze

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

Stwarza to ostrzeżenie i pozwala, aby przejść do ekranu ustawień i nacisnąć przycisk Wstecz, aby przyjść z powrotem do swojej aplikacji. Wykrywacz widżetów mocy nie działa zgodnie z moją wiedzą.

2

użyć tego kodu // turnGPSON zwany Po 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

Myślę, że mamy więcej lepszą wersję, aby umożliwić lokalizację bez otwierania ustawienia podobnie jak Google współpracuje z mapami.

Będzie wygląda następująco -

enter image description here

Dodaj Zależność w Gradle - kompilacji 'com.google.android.gms play-Services lokalizację: 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(); 
     } 
    } 
} 
Powiązane problemy