Abdul Wahab Abdul Wahab - 1 month ago 19
Android Question

Why is code after runtime permission call being executed first?

In my

onCreate()
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?

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

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)
{

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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

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().

Comments