为什么先执行运行时权限调用之后的代码?
Why is code after runtime permission call being executed first?
在我的 onCreate()
方法中,我显示了一个在权限选择对话框出现之前正在执行的 Toast,即使我首先请求权限也是如此。为什么吐司最先出现?
@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();
}
您调用的 requestPermissions
方法异步运行,因此一旦该调用进入新线程并且 returns 进入主线程,Toast 可能会出现在对话框之前。这仅取决于在后台完成了多少工作以及哪个线程更快。
有关权限和异步部分的更多信息,请查看此处的文档: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().
在我的 onCreate()
方法中,我显示了一个在权限选择对话框出现之前正在执行的 Toast,即使我首先请求权限也是如此。为什么吐司最先出现?
@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();
}
您调用的 requestPermissions
方法异步运行,因此一旦该调用进入新线程并且 returns 进入主线程,Toast 可能会出现在对话框之前。这仅取决于在后台完成了多少工作以及哪个线程更快。
有关权限和异步部分的更多信息,请查看此处的文档: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().