Reputation: 1899
I'm trying to request permissions from AsyncTask
called by a android.support.v4.app.Fragment
.
On doInBackground
method has this piece of code
int hasWriteContactsPermission = ContextCompat.checkSelfPermission((Context)ctx,
Manifest.permission.SEND_SMS);
if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
if (!ActivityCompat.shouldShowRequestPermissionRationale((AppCompatActivity)ctx,
Manifest.permission.SEND_SMS)) {
showMessageOKCancel("Necessary permissions", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
requestPermissions(new String[]{Manifest.permission.SEND_SMS},
REQUEST_CODE_ASK_PERMISSIONS);
}
});
return;
}
/******** PROBLEM
requestPermissions(new String[] {Manifest.permission.SEND_SMS},
REQUEST_CODE_ASK_PERMISSIONS);
*************/
return;
}
Calling requestPermissions through AppCompatActivity is not valid for me because i need to catch onRequestPermissionsResult
in Fragment
, not in Activity
The problem is that requestPermissions says this error:
Cannot resolve method requestPermissions
How can i call requestPermissions
method from Asynctask
to catch the result on the caller Fragment?
Upvotes: 2
Views: 2667
Reputation: 41
Actually you cannot ask for permission inside the doInBackground method, because as the name says, it is doing work in backgorund, and requesting permissions to the user needs to use UI thread. I suggest to you calling a request permission like this:
public void checkPermissions() {
final String[] permissions = new String[]{Manifest.permission.SEND_SMS}
if ( ContextCompat.checkSelfPermission(this,
android.Manifest.permission.SEND_SMS )
!= PackageManager.PERMISSION_GRANTED ) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
android.Manifest.permission.SEND_SMS )){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Permission Needed");
builder.setMessage("You must accept the permission.");
builder.setPositiveButton(R.string.global_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ActivityCompat.requestPermissions(ConfigurarActivity.this,
permissions,
PERMISSION_REQUEST);
}
});
builder.setNegativeButton(R.string.global_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
ActivityCompat.requestPermissions(this,
permissions,
PERMISSION_REQUEST);
}
}else{
//doTaskThatNeedThePermission can be async
}
}
Upvotes: 4
Reputation: 1
You can execute requestPermissions
if you have an Activity reference
// in your Activity
final Activity act = this;
// onClick
act.requestPermissions(new String[]{Manifest.permission.SEND_SMS},
REQUEST_CODE_ASK_PERMISSIONS);
Upvotes: -2