Created
September 4, 2015 19:51
-
-
Save MariusVolkhart/618a51bb09c4fc7f86a4 to your computer and use it in GitHub Desktop.
Android M Permission Sample using Support Fragment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
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.
The result wont be returned to support fragment, it will be returned to parent activity with this call.
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
What if my app is not targeting M? Would this work?