You can do it like this,
In Manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
In Activity where you want this permission request:
final int REQUEST_ID_PERMISSIONS = 1;
shar_btn = (Button) findViewById(R.id.shrbtn);
shar_btn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (checkAndRequestPermissions()) {
// call comman function that you want to execute
shareLocation();
}
}
});
Then for the checkAndRequestPermissions() function,
/**
* Check the permission for the ACCESS_FINE_LOCATION
* if already accepted the permission then pass true
* else ask permission for the ACCESS_FINE_LOCATION
*
* @return
*/
private boolean checkAndRequestPermissions() {
int externalStoragePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
List<String> listPermissionsNeeded = new ArrayList<>();
if (externalStoragePermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_PERMISSIONS);
return false;
}
return true;
}
If the user accepts it once, then your app will remember it and you won't need to send this Permission Dialog anymore. Note that the user could disable it later if he decided to.
Then before requesting the location, you would have to test if the permission is still granted :
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_ID_PERMISSIONS: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
shareLocation();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
And your ShareLocation() like,
private void shareLocation(){
link = formatLocation(getLocation(), getResources().getStringArray(R.array.link_templates)[0]);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, link);
intent.setType("text/plain");
startActivity(Intent.createChooser(intent, getString(R.string.share_location_via)));
}