onRequestPermissionsResult callback must wait method call requestPermissions finish

i'm trying to get result of a requestPermissions(..) by using a sleep loop and wait for user response, but the callback method onRequestPermissionsResult(..) must wait for the method which call requestPermissions finish to execute, so I cant get it as well.

Example code :

public int result = 0;

public int askSystemForPermission(String permission)
{
   result = 0;
   requestPermissions(this,new String[] {permission});

   while (result == 0)                  // It hang forever here
   {                                    // because onRequestPermissionsResult never excute
      try {                             // then result always equals to 0
          Thread.sleep(500);
      } catch (Exception ecx) {}
   }

   return result;
}


public void onRequestPermissionsResult(...)
{
   if ( /*granted*/ )
   {
       result = 1;
   }
   else if ( /*dont show again*/ )
   {
       result = 2;
   }
   else //denied
   {
       result = 3;
   }
}

I've tried some solution : Put requestPermissions in new Thread(), runOnUiThread() .. still the same. Call requestPermissions from other Activity, the new Activity dont even start, it still wait askSystemForPermission method finish.

P/S : It can be done in others way but i want to know why android act like this and how to resolve this problem.

Upvotes: 1

Views: 1971

Answers (1)

Nick Cardoso
Nick Cardoso

Reputation: 21773

Requesting permissions is an asynchronous task, your unsynchronised result variable will always be 0 forever because the rest of the code in that method and the request callback happen in different threads (think alternate timelines).

What you need to do is first check if you already have permission

if (ContextCompat.checkSelfPermission(thisActivity, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(thisActivity, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}

If you don't then you request permission, but you wait for it by overriding another method and doing your work from there:

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)

This does of course mean your method can't return result - you can't run something asynchronously and have your method wait for it blocking a thread (thus leaving that thread unavailable even for a callback)

(Note: MY_PERMISSIONS_REQUEST_READ_CONTACTS is a self defined request code)

Upvotes: 1

Related Questions