I have a class that extends from DialogPreference
which allows the user to choose from their calendars. As of Android M, the user must grant permission at runtime for the app to access the calendars. In an Activity
or a Fragment
, this would normally be relatively straightforward: a call to ActivityCompat.requestPermissions(Activity [...])
or FragmentCompat.requestPermissions(Fragment [...])
would do the trick.
However, in a DialogPreference
, there is no obvious way of accessing the Activity
or Fragment
that uses the DialogPreference
. getContext()
cannot be guaranteed to refer to an Activity, so casting that to an Activity
may be unreliable. Using instanceOf
smacks of ugliness, and does not solve the issue where getContext()
does not refer to an Activity
.
getDialog().getOwnerActivity()
looks promising, but returns null when it is needed (e.g. during the DialogPreference
's onBindView()
method).
What is the best practice for requesting permissions needed by a Preference
? Should the request for permissions be removed completely from the Preference
and placed in the PreferenceFragment
?
Should the request for permissions be removed completely from the Preference and placed in the PreferenceFragment?
IMHO, yes. Or, more accurately: request the permissions before showing the preferences.