Abdul Wahab Abdul Wahab - 9 months ago 54
Android Question

Why is code after runtime permission call being executed first?

In my

method I show a Toast that is executing before the permission selection dialog box appears, even though I call for permission first. Why is the toast showing up first?

protected void onCreate(Bundle savedInstanceState) {

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

provider = locationManager.getBestProvider(new Criteria(), false);

if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)

requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_CODE);


Toast.makeText(MainActivity.this, "oncreate", Toast.LENGTH_SHORT).show();


Answer Source

The requestPermissions method you call runs asynchronously, so once that call goes to a new thread and it returns to the main one, the Toast may appear prior to the dialog. It simply depends on how much work is done in the background and which thread is faster.

For more information on permissions and the asynchronous part, check the docs here: https://developer.android.com/training/permissions/requesting.html#perm-request

This method functions asynchronously: it returns right away, and after the user responds to the dialog box, the system calls the app's callback method with the results, passing the same request code that the app passed to requestPermissions().