J'essaie de créer une application qui envoie des mises à jour de localisation d'un utilisateur toutes les cinq minutes. Je suppose que mon code fonctionne très bien, mais j'obtiens une erreur concernant les autorisations utilisées par l'application. Je suis à peu près sûr d'avoir ajouté les autorisations dans le fichier manifeste. Quelqu'un peut-il me dire ce qui ne va pas? Voici mon code.
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
}
}
Je reçois une erreur en tant que l'appel nécessite une autorisation qui peut être rejetée par l'utilisateur dans ces lignes-
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider,5*60*1000,0,this);
Mon AndroidManifest est comme ça
<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>
Quel SDK utilisez-vous? Si vous utilisez Marshmallow, vous devez vérifier que l'utilisateur a accordé une autorisation pour chaque appel d'emplacement.
Jetez un oeil ici.
Vous devriez faire quelque chose comme ça:
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
);
}
demander la permission si vous ne l'avez pas déjà.
vérifiez le lien ci-dessus pour plus d'informations.
Essayez mon code:
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;
}
}
}
}
Source: LIEN
Cela a fonctionné pour moi
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) {
Toast.makeText(YourService.this, "First enable LOCATION ACCESS in settings.", Toast.LENGTH_LONG).show();
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 1, listener);
Voici le tas d'étapes que vous devez effectuer pour résoudre ce problème
Activité 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
Maintenant, vous devez également mettre à jour votre build.gradle
dependencies{
------------- //your pre-generated code
compile 'com.Android.support:support-v4:23.0.1'
}
this est ce que Android.Developers en dit.
Et n'oubliez pas de donner des autorisations à partir des paramètres de l'application si vous utilisez un émulateur, car il se peut que l'invite ne soit pas invitée à le faire