Activity.requestPermissions vs ActivityCompat.requestPermissions

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 00:56:32

问题


Runtime permission dialog is shown in Android 6.0 or higher, so Activity.requestPermissions(...) which was added in API level 23 makes sense.

But why is there another one (ActivityCompat.requestPermissions(...)) to be used for below Android 6.0? Does this show runtime permission request dialog in lower versions?


  • What is the difference between

    Activity.requestPermissions(permissions, requestCode)
    

    and

    ActivityCompat.requestPermissions(activity, permissions, requestCode)
    
  • Which one should I use?


回答1:


Does this show runtime permission request dialog in lower versions?

No. There is no such dialog on lower versions. It will simply call your onRequestPermissionsResult() method to let you know that you hold the permissions (since, by definition, you already do).

What is the difference between

Activity#requestPermissions() is for apps with a minSdkVersion of 23 or higher, or for apps whose developers like calling if (Build.VERSION.SDK_INT >= 23) to avoid that call on older devices.

ActivityCompat.requestPermissions() is for any app, as it "does the right thing" on all supported API levels (back to API Level 14 IIRC).

Which one should I use?

If your minSdkVersion is 23 or higher, feel free to use Activity#requestPermissions(). Otherwise, I recommend ActivityCompat.requestPermissions().




回答2:


But why is there another one (ActivityCompat.requestPermissions(...)) to be used for below Android 6.0?

It exists because there are two types of Acvivity in Android, android.app.Activity docs, and android.support.v4.app.ActivityCompatdocs.

  • Activity is for use in devices whose min SDK version is 14 iirc
  • ActivityCompat is for backwards compatibility (SDK 9 and above). It allows you to have access to supportable new features and Material themes without any of the breaking changes that the new OS versions introduced to achieve the new features and UI.

Does this show runtime permission request dialog in lower versions?

No. Android 6.0 is the first to show runtime Permission dialogs and as such previous versions of Android cannot show them. That bit of code is actually ignored by previous versions of the OS iirc.

Which one should I use?

That wholly depends on which type of Activity you are using. If your activity is a child of Activity then use Activity.requestPermissions(permissions, requestCode). if you are using a child of ActivityCompat however, use ActivityCompat.requestPermissions(activity, permissions, requestCode).



来源:https://stackoverflow.com/questions/56761066/activity-requestpermissions-vs-activitycompat-requestpermissions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!