gpt4 book ai didi

android - 为什么先执行运行时权限调用之后的代码?

转载 作者:行者123 更新时间:2023-11-29 17:11:47 25 4
gpt4 key购买 nike

在我的 onCreate() 方法中,我显示了一个在权限选择对话框出现之前正在执行的 Toast,即使我首先请求权限也是如此。为什么 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 方法异步运行,因此一旦该调用转到新线程并返回到主线程,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().

关于android - 为什么先执行运行时权限调用之后的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40226649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com