2015-10-25 16 views
10

Sto provando a creare un'applicazione che invii aggiornamenti di posizione di un utente ogni cinque minuti. Suppongo che il mio codice funzioni correttamente ma ottengo un errore riguardo le autorizzazioni che vengono utilizzate dall'applicazione. Sono abbastanza sicuro di aver aggiunto le autorizzazioni nel file manifest. Qualcuno può dirmi cosa c'è che non va? Ecco il mio codice.La chiamata richiede autorizzazioni che possono essere rifiutate dall'utente

MainActivity.java

LocationManager locationManager ; 
String provider; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Getting LocationManager object 
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

    // Creating an empty criteria object 
    Criteria criteria = new Criteria(); 

    // Getting the name of the provider that meets the criteria 
    provider = locationManager.getBestProvider(criteria, false); 

    if(provider!=null && !provider.equals("")){ 

     // Get the location from the given provider 
     Location location = locationManager.getLastKnownLocation(provider); 
     locationManager.requestLocationUpdates(provider,5*60*1000,0,this); 

     if(location!=null) 
      onLocationChanged(location); 
     else 
      Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show(); 

    }else{ 
     Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show(); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
} 

@Override 
public void onLocationChanged(Location location) { 
    // Getting reference to TextView tv_longitude 
    TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude); 

    // Getting reference to TextView tv_latitude 
    TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude); 

    // Setting Current Longitude 
    tvLongitude.setText("Longitude:" + location.getLongitude()); 

    // Setting Current Latitude 
    tvLatitude.setText("Latitude:" + location.getLatitude()); 
} 

@Override 
public void onProviderDisabled(String provider) { 
    // TODO Auto-generated method stub 
} 

@Override 
public void onProviderEnabled(String provider) { 
    // TODO Auto-generated method stub 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
    // TODO Auto-generated method stub 
} 

}

sto ottenendo un errore come chiamata richiede l'autorizzazione che può essere rifiutata dall'utente in queste linee-

Location location = locationManager.getLastKnownLocation(provider); 
     locationManager.requestLocationUpdates(provider,5*60*1000,0,this); 

mio AndroidManifest è come quello s

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

<application 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/title_activity_main" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

risposta

25

Quale SDK si usa? Se si utilizza Marshmallow, è necessario verificare che l'utente abbia concesso l'autorizzazione per ogni chiamata di posizione.

Date un'occhiata Here.

Si dovrebbe fare qualcosa di simile:

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 

      ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.ACCESS_COARSE_LOCATION }, 
               LocationService.MY_PERMISSION_ACCESS_COURSE_LOCATION); 
     } 

richiesta l'autorizzazione se non avete già.

controllare il collegamento sopra per maggiori informazioni.

+0

Sto usando Android 4.2 e superiori. –

+1

devi compilare usando l'SDK 23, non c'è altra spiegazione.per favore controlla che nel file gradle del tuo app – Shahar

+0

Sì avevi ragione! Si stava compilando usando l'SDK 23. Grazie a ciò è stato risolto il problema. –

13

Prova il mio codice:

public class MainActivity extends AppCompatActivity { 

    /* GPS Constant Permission */ 
    private static final int MY_PERMISSION_ACCESS_COARSE_LOCATION = 11; 
    private static final int MY_PERMISSION_ACCESS_FINE_LOCATION = 12; 

    /* Position */ 
    private static final int MINIMUM_TIME = 10000; // 10s 
    private static final int MINIMUM_DISTANCE = 50; // 50m 

    /* GPS */ 
    private String mProviderName; 
    private LocationManager mLocationManager; 
    private LocationListener mLocationListener; 

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

     mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     // Get the best provider between gps, network and passive 
     Criteria criteria = new Criteria(); 
     mProviderName = mLocationManager.getBestProvider(criteria, true); 

     // API 23: we have to check if ACCESS_FINE_LOCATION and/or ACCESS_COARSE_LOCATION permission are granted 
     if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
       || ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) { 

      // No one provider activated: prompt GPS 
      if (mProviderName == null || mProviderName.equals("")) { 
       startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
      } 

      // At least one provider activated. Get the coordinates 
      switch (mProviderName) { 
       case "passive": 
        mLocationManager.requestLocationUpdates(mProviderName, MINIMUM_TIME, MINIMUM_DISTANCE, this); 
        Location location = mLocationManager.getLastKnownLocation(mProviderName); 
        break; 

       case "network": 
        break; 

       case "gps": 
        break; 

      } 

     // One or both permissions are denied. 
     } else { 

      // The ACCESS_COARSE_LOCATION is denied, then I request it and manage the result in 
      // onRequestPermissionsResult() using the constant MY_PERMISSION_ACCESS_FINE_LOCATION 
      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
         MY_PERMISSION_ACCESS_COARSE_LOCATION); 
      } 
      // The ACCESS_FINE_LOCATION is denied, then I request it and manage the result in 
      // onRequestPermissionsResult() using the constant MY_PERMISSION_ACCESS_FINE_LOCATION 
      if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       ActivityCompat.requestPermissions(this, 
         new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, 
         MY_PERMISSION_ACCESS_FINE_LOCATION); 
      } 

     } 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSION_ACCESS_COARSE_LOCATION: { 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // permission was granted 
       } else { 
        // permission denied 
       } 
       break; 

      case MY_PERMISSION_ACCESS_FINE_LOCATION: { 
       if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // permission was granted 
       } else { 
        // permission denied 
       } 
       break; 
      } 

     } 
    } 
} 

Fonte: LINK

+1

È possibile chiamare 'requestPermission' solo dopo aver passato entrambe le autorizzazioni all'interno dell'array, –

+0

@ ThiagoPorciúncula cercherò :) Grazie per il suggerimento – eldivino87

+1

Potrebbe non fare alcuna differenza a causa di [Gruppi di autorizzazioni] (http: // developer .android.com/intl/it-it/guide/argomenti/security/permissions.html # Perm-gruppi). Quando ottieni l'autorizzazione per "ACCESS_FINE_LOCATION", ottieni automaticamente "ACCESS_COARSE_LOCATION", poiché appartengono allo stesso gruppo ('LOCATION'). Vedi di più su questo qui: http://developer.android.com/intl/pt-br/training/permissions/requesting.html –

4

Questo ha funzionato per me

if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
     // TODO: Consider calling 
     // ActivityCompat#requestPermissions 
     // here to request the missing permissions, and then overriding 
     // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
     //           int[] grantResults) 
     // to handle the case where the user grants the permission. See the documentation 
     // for ActivityCompat#requestPermissions for more details. 
     Toast.makeText(YourService.this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show(); 
     return; 
    } 
     locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, listener); 
+1

Questo è giusto, per qualsiasi ragione Android Studio genera un errore se non si inserisce questo esatto codice quando si richiede la posizione, anche se si gestiscono le autorizzazioni in un altro modo personalizzato. – Sca09

2

Ecco il gruppo di passi da eseguire per risolvere questo

Attività principale .java

if (ContextCompat.checkSelfPermission(this, 
android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED 
|| ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) 
== PackageManager.PERMISSION_GRANTED) {   
locationManager.requestLocationUpdates 
(locationManager.requestLocationUpdates(provider,5*60*1000,0,this); 
}//end of if 

Ora è anche bisogno di aggiornare il tuo build.gradle

dependencies{ 
------------- //your pre-generated code 
compile 'com.android.support:support-v4:23.0.1' 
} 

this è ciò Android.Developers dicono su di esso.

E non dimenticate di dare i permessi da impostazioni dell'applicazionese si sta utilizzando un emulatore, perché non potrebbe essere richiesto per tale

Problemi correlati