我有一个课程,从DialogPreference
延伸,允许用户从他们的日历中进行选择。从Android M开始,用户必须在运行时授予应用程序访问日历的权限。在Activity
或Fragment
中,这通常会相对简单:拨打ActivityCompat.requestPermissions(Activity [...])
或FragmentCompat.requestPermissions(Fragment [...])
可以解决问题。如何从自定义首选项请求权限?
但是,在DialogPreference
中,没有明显的方式访问使用DialogPreference
的Activity
或Fragment
。 getContext()
不能保证引用一个活动,因此将其转换为Activity
可能不可靠。使用instanceOf
丑陋的痕迹,并没有解决getContext()
不指Activity
的问题。
getDialog().getOwnerActivity()
看起来很有希望,但在需要时返回null(例如在DialogPreference
的onBindView()
方法中)。
要求Preference
所需权限的最佳做法是什么?应该从Preference
中完全删除权限请求并将其置于PreferenceFragment
?