Skip to content

Instantly share code, notes, and snippets.

@MariusVolkhart
Created September 4, 2015 19:51
Show Gist options
  • Save MariusVolkhart/618a51bb09c4fc7f86a4 to your computer and use it in GitHub Desktop.
Save MariusVolkhart/618a51bb09c4fc7f86a4 to your computer and use it in GitHub Desktop.
Android M Permission Sample using Support Fragment
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
// ... Some magical things
if (ContextCompat.checkSelfPermission(getActivity(), READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
// We have access. Life is good.
setupContactsPicker();
} else if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), READ_CONTACTS)) {
// We've been denied once before. Explain why we need the permission, then ask again.
getActivity().showDialog(DIALOG_PERMISSION_REASON);
} else {
// We've never asked. Just do it.
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_PERMISSION_CONTACTS);
}
return magicalView;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_PERMISSION_CONTACTS && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setupContactsPicker();
} else {
// We were not granted permission this time, so don't try to show the contact picker
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
@JenniferVanderputten
Copy link

If you are not supporting M then you don't need to request permissions, pre-M will force permissions acceptance as a condition of installation. You could wrap this in a version check in order to support M and pre-M.

@pqtuan86
Copy link

The result wont be returned to support fragment, it will be returned to parent activity with this call.

@abs51295
Copy link

I think requestPermissions would pass the results to the fragment itself. You can refer this answer on SO.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment