将这些添加到您的AndroidManifest.xml
before application
tag
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
另外对于Android版本> = 23,您需要在运行时请求位置权限
if (ContextCompat.checkSelfPermission(YourActivity.this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(YourActivity.this,
Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
askForLocationPermissions();
} else {
//do your work
}
And
private void askForLocationPermissions() {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new android.support.v7.app.AlertDialog.Builder(this)
.setTitle("Location permessions needed")
.setMessage("you need to allow this permission!")
.setPositiveButton("Sure", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(YourActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
}
})
.setNegativeButton("Not now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// //Do nothing
}
})
.show();
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
LOCATION_PERMISSION_REQUEST_CODE);
// MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
Also
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
switch (requestCode) {
case LOCATION_PERMISSION_REQUEST_CODE:
if (isPermissionGranted(permissions, grantResults, Manifest.permission.ACCESS_FINE_LOCATION)) {
//Do you work
} else {
Toast.makeText(this, "Can not proceed! i need permission" , Toast.LENGTH_SHORT).show();
}
break;
}
}
And
public static boolean isPermissionGranted(@NonNull String[] grantPermissions, @NonNull int[] grantResults,
@NonNull String permission) {
for (int i = 0; i < grantPermissions.length; i++) {
if (permission.equals(grantPermissions[i])) {
return grantResults[i] == PackageManager.PERMISSION_GRANTED;
}
}
return false;
}