应该如何从自定义首选项请求权限?
How should one request permissions from a custom Preference?
我有一个从 DialogPreference
扩展而来的 class,它允许用户从他们的日历中进行选择。从 Android M 开始,用户必须在运行时授予应用程序访问日历的权限。在 Activity
或 Fragment
中,这通常会相对简单:调用 ActivityCompat.requestPermissions(Activity [...])
或 FragmentCompat.requestPermissions(Fragment [...])
即可。
但是,在 DialogPreference
中,没有明显的方法可以访问使用 DialogPreference
的 Activity
或 Fragment
。 getContext()
不能保证指向 Activity,因此将其转换为 Activity
可能不可靠。使用 instanceOf
有点丑陋,并且不能解决 getContext()
不引用 Activity
.
的问题
getDialog().getOwnerActivity()
看起来很有前途,但 returns 在需要时为空(例如在 DialogPreference
的 onBindView()
方法期间)。
请求 Preference
所需权限的最佳做法是什么?是否应将权限请求从 Preference
中完全删除并放在 PreferenceFragment
中?
Should the request for permissions be removed completely from the Preference and placed in the PreferenceFragment?
恕我直言,是的。或者,更准确地说:在显示首选项之前请求权限。
我的项目TestPreferenceFragment extends PreferenceFragment{...}
.
不要回调onRequestPermissionsResult
当我使用操作时:
getActivity().requestPermissions(……)
ActivityCompat.requestPermissions(getActivity(),……)
然后我通过以下方式修复它:PreferenceFragment.requestPermissions()
在片段中,仅使用
请求许可
requestPermissions(permissionList, REQUEST_CODE)
而不是
ActivityCompat.requestPermission(Activity, String[], int)
我有一个从 DialogPreference
扩展而来的 class,它允许用户从他们的日历中进行选择。从 Android M 开始,用户必须在运行时授予应用程序访问日历的权限。在 Activity
或 Fragment
中,这通常会相对简单:调用 ActivityCompat.requestPermissions(Activity [...])
或 FragmentCompat.requestPermissions(Fragment [...])
即可。
但是,在 DialogPreference
中,没有明显的方法可以访问使用 DialogPreference
的 Activity
或 Fragment
。 getContext()
不能保证指向 Activity,因此将其转换为 Activity
可能不可靠。使用 instanceOf
有点丑陋,并且不能解决 getContext()
不引用 Activity
.
getDialog().getOwnerActivity()
看起来很有前途,但 returns 在需要时为空(例如在 DialogPreference
的 onBindView()
方法期间)。
请求 Preference
所需权限的最佳做法是什么?是否应将权限请求从 Preference
中完全删除并放在 PreferenceFragment
中?
Should the request for permissions be removed completely from the Preference and placed in the PreferenceFragment?
恕我直言,是的。或者,更准确地说:在显示首选项之前请求权限。
我的项目TestPreferenceFragment extends PreferenceFragment{...}
.
不要回调onRequestPermissionsResult
当我使用操作时:
getActivity().requestPermissions(……)
ActivityCompat.requestPermissions(getActivity(),……)
然后我通过以下方式修复它:PreferenceFragment.requestPermissions()
在片段中,仅使用
请求许可requestPermissions(permissionList, REQUEST_CODE)
而不是
ActivityCompat.requestPermission(Activity, String[], int)