Sie sind auf Seite 1von 29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Everything every Android


Developer must know about new
Android's Runtime Permission
Posted on 26 Aug 2015 05:16 | 57137 reads | 298 shares

(/blog/things-you-need-to-know-about-android-mpermission-developer-edition/en)

(/blog/things-you-need-to-

know-about-android-m-permission-developer-edition/th)

Android M's name was just announced officially days ago. The final
version is almost thereand would be released not so long.
Although Android is being keep developedbut the latest update to
Android M is totally different since there is some major change that
would change everything like new Runtime Permission. Surprisingly
it is not much talked about in Android Developer community even
though it is extremely important and may cause somebig trouble in
the near future.
That's the reason why Idecide to blog about this topic today.
Everything you needto know about this new Runtime Permission
including how to implement it in your code. Let's do it before it's too
late.

The New Runtime Permission

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

1/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

The New Runtime Permission


Android's permission system is one of the biggest security concern
all along since those permissions areasked for at install time. Once
installed, the application will be able to access all of things granted
without any user's acknowledgement what exactly application does
with the permission.
No surprise why there are so many bad guys trying to collect user's
personal data through this security weakness and use it in the bad
way.
Android team also knowthis concern. 7 year passed, finally
permission system is redesigned. In Android 6.0 Marshmallow,
application will not be granted any permission at installation
time. Instead, application has to ask user for a permission oneby-one at runtime.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

2/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Please note that permission request dialog shown above will


notlaunch automatically. Developer has to call for it manually. In the
case that developertry to call some functionthat requires a
permission whichuser has not granted yet, the functionwill
suddenly throw an Exception which will lead to the application
crashing.

Besides, user is alsoable to revoke the granted permission anytime


through phone's Settings application.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

3/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

You might already feel like there is some cold wind blowing through
your arms ... If you are an Android Developer, you will suddenly
know that programming logic is totally changed. You cannot just call
a function to do the job like previous but you have to check for the
permission for every single feature or your application will just
simply crash !
Correct. I would not spoil you that it is easy. Although it is a great
thingfor user but it is truly nightmare for us developer. We have to
take coding to the next level or it will surely have a problem in both
short-term and long-term.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

4/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Anyway this new Runtime Permission will work like described only
when we set the application's targetSdkVersion to 23 which mean it
is declared that applicationhas already been tested on API Level 23.
And this feature will work only on Android 6.0 Marshmallow. The
same app will run with same old behavior on pre-Marshmallow
device.

What happened to the application


that has already been launched?
This new permission system may cause you some panic right now.
"Hey ! What's about my application that launched 3 years ago. If
it is installed on Android 6.0 device, does this behavior also
applied? Willmy application also crash?!?"
Don't worry. Android team has already thought about it. If the
application's targetSdkVersion is set to less than 23. It will be
assumed that application is not tested with newpermission
system yet and will switch to the same old behavior: user has to
accept every single permission at install time and they will be
all granted once installed !

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

5/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

As a result, application will run perfectly likeprevious.


Anywayplease note that user still can revoke a permission after
that !AlthoughAndroid 6.0 warn the userwhen they try to do that
but they can revoke anyway.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

6/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Next question in your head right now. So will my application crash?


Such a kindness sent from god delivered through the Android team.
When we call a function that requires a permission user revoked on
application withtargetSdkVersion less than 23, no anyException will
be thrown. Instead it will just simply do nothing. For the function that
return value, it will return either null or 0depends on the case.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

7/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

But don't be too happy. Although application would not be crashed


from calling a function. It may still cancrash from whatthat
applicationdoes next with those returned value.
Good news(at least for now)is these cases may rarely occur since
this permission revoking feature is quite new and I believe that just
few user willdo it. In case they do, they have to accept the result.
But in the long run, I believe that there will be millions of users
whoturn some permission off. Letting our application not to
workperfectly on new device is not acceptable.
To make it work perfectly, youbetter modify yourapplication to
support this new permission system and I suggest you to startdoing
it right now !
For thatapplication which source code is not successfully modified
to support Runtime Permission, DO NOT release itwith
targetSdkVersion 23 or it will cause you a trouble. Move the
targetSdkVersion to 23 only when you pass all the test.
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

8/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Warning: Right now when you create a new project in Android Studio.
targetSdkVersion will be automatically set to the latest version, 23. If you
are not ready to make your application fully support the Runtime
Permission, I suggest you to step downthe targetSdkVersion to 22 first.

Automatically granted permissions


There is some permission that will be automatically granted at install
time and will not be able to revoke. We call it Normal Permission
(https://developer.android.com/preview/features/runtimepermissions.html#normal) (PROTECTION_NORMAL). Here is the full
list of them:
android.permission.ACCESS_LOCATION_EXTRA_COMMANDS
android.permission.ACCESS_NETWORK_STATE
android.permission.ACCESS_NOTIFICATION_POLICY
android.permission.ACCESS_WIFI_STATE
android.permission.ACCESS_WIMAX_STATE
android.permission.BLUETOOTH
android.permission.BLUETOOTH_ADMIN
android.permission.BROADCAST_STICKY
android.permission.CHANGE_NETWORK_STATE
android.permission.CHANGE_WIFI_MULTICAST_STATE
android.permission.CHANGE_WIFI_STATE
android.permission.CHANGE_WIMAX_STATE
android.permission.DISABLE_KEYGUARD
android.permission.EXPAND_STATUS_BAR
android.permission.FLASHLIGHT
android.permission.GET_ACCOUNTS
android.permission.GET_PACKAGE_SIZE
android.permission.INTERNET
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

9/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

android.permission.KILL_BACKGROUND_PROCESSES
android.permission.MODIFY_AUDIO_SETTINGS
android.permission.NFC
android.permission.READ_SYNC_SETTINGS
android.permission.READ_SYNC_STATS
android.permission.RECEIVE_BOOT_COMPLETED
android.permission.REORDER_TASKS
android.permission.REQUEST_INSTALL_PACKAGES
android.permission.SET_TIME_ZONE
android.permission.SET_WALLPAPER
android.permission.SET_WALLPAPER_HINTS
android.permission.SUBSCRIBED_FEEDS_READ
android.permission.TRANSMIT_IR
android.permission.USE_FINGERPRINT
android.permission.VIBRATE
android.permission.WAKE_LOCK
android.permission.WRITE_SYNC_SETTINGS
com.android.alarm.permission.SET_ALARM
com.android.launcher.permission.INSTALL_SHORTCUT
com.android.launcher.permission.UNINSTALL_SHORTCUT

Just simply declare those permissions in AndroidManifest.xml and it


will work just fine. No need to check for the permission listed above
since itcouldn't be revoked.

Make your applicationsupport new


Runtime Permission
Now it's time to make our application support new Runtime
Permission perfectly. Start with setting
compileSdkVersion and targetSdkVersion to 23.
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

10/29

1/11/2016

1
2
3
4
5
6
7
8
9

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

android{
compileSdkVersion23
...

defaultConfig{
...
targetSdkVersion23
...
}

In this example, we try to add a contact with a function below.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

privatestaticfinalStringTAG="Contacts";
privatevoidinsertDummyContact(){
//Twooperationsareneededtoinsertanewcontact.
ArrayList<ContentProviderOperation>operations=newArrayList<Conte

//First,setupanewrawcontact.
ContentProviderOperation.Builderop=
ContentProviderOperation.newInsert(ContactsContract.RawConta
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME
operations.add(op.build());

//Next,setthenameforthecontact.
op=ContentProviderOperation.newInsert(ContactsContract.Data.CONTEN
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONT
.withValue(ContactsContract.CommonDataKinds.StructuredName.D
"__DUMMYCONTACTfromruntimepermissionssample"
operations.add(op.build());

//Applytheoperations.
ContentResolverresolver=getContentResolver();
try{
resolver.applyBatch(ContactsContract.AUTHORITY,operations);
}catch(RemoteExceptione){
Log.d(TAG,"Couldnotaddanewcontact:"+e.getMessage());
}catch(OperationApplicationExceptione){
Log.d(TAG,"Couldnotaddanewcontact:"+e.getMessage());
}
}

The above code requires WRITE_CONTACTS permission. If it is called


without this permission granted, application will suddenly crash.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

11/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Next step is to add a permission into AndroidManifest.xml with


same old method.
1

<usespermissionandroid:name="android.permission.WRITE_CONTACTS"/>

Next step iswe have to create another function to check


thatpermission is granted or not. If it isn'tthencall a dialog to ask
user for a permission. Otherwise, you can go on the next step,
creating a new contact.
Permissionsaregrouped into Permission Group like table below.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

12/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

If any permission in a Permission Group is granted. Another


permission in the same group will be automatically granted as well.
In this case, once WRITE_CONTACTS is granted, application will also
grant READ_CONTACTS and GET_ACCOUNTS .
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

13/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Source code used to check and ask for permission is Activity's


checkSelfPermission and requestPermissions respectively. These

methods are added in API Level 23.


1
2
3
4
5
6
7
8
9
10
11

finalprivateintREQUEST_CODE_ASK_PERMISSIONS=123;

privatevoidinsertDummyContactWrapper(){
inthasWriteContactsPermission=checkSelfPermission(Manifest.permis
if(hasWriteContactsPermission!=PackageManager.PERMISSION_GRANTED)
requestPermissions(newString[]{Manifest.permission.WRITE_CONTA
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
insertDummyContact();
}

If permission has already been granted, insertDummyContact() will


be suddenly called. Otherwise, requestPermissions will be calledto
launch a permission request dialog like below.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

14/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

No matterAllow or Deny is chosen, Activity's


onRequestPermissionsResult will always be called to inform a result

which we can check fromthe 3rd parameter, grantResults , like this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

@Override
publicvoidonRequestPermissionsResult(intrequestCode,String[]permiss
switch(requestCode){
caseREQUEST_CODE_ASK_PERMISSIONS:
if(grantResults[0]==PackageManager.PERMISSION_GRANTED){
//PermissionGranted
insertDummyContact();
}else{
//PermissionDenied
Toast.makeText(MainActivity.this,"WRITE_CONTACTSDenied
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode,permissions,g
}
}

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

15/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

This is how Runtime Permission works. Code is quite complicated


but be used toit ... To make you application works perfectly with
Runtime Permission, you have to handle all the case with the same
method shown above.
If you want to punch some wall, it is a good time now ...

Handle "Never Ask Again"


If user denied a permission. In the second launch, user will get a
"Never ask again" option to prevent application from asking this
permission in the future.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

16/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

If this option is checked before denying. Next time we call


requestPermissions , this dialog will not be appeared for this kind of

permission anymore. Instead, it just does nothing.


However it is quite bad in term of UX if user does something but
there is nothing interact back. This case has to be handled as well.
Before calling requestPermissions , we need to check thatshould we
show a rationale about why application needs the being-requested
permission through
Activity's shouldShowRequestPermissionRationale method. Source
code will now look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

finalprivateintREQUEST_CODE_ASK_PERMISSIONS=123;

privatevoidinsertDummyContactWrapper(){
inthasWriteContactsPermission=checkSelfPermission(Manifest.permis
if(hasWriteContactsPermission!=PackageManager.PERMISSION_GRANTED)
if(!shouldShowRequestPermissionRationale(Manifest.permissio
showMessageOKCancel("YouneedtoallowaccesstoContact
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
requestPermissions(newString[]{Manifes
REQUEST_CODE_ASK_PERMISSIONS);
}
});
return;
}
requestPermissions(newString[]{Manifest.permission.WRITE_CONTA
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
insertDummyContact();
}

privatevoidshowMessageOKCancel(Stringmessage,DialogInterface.OnClick
newAlertDialog.Builder(MainActivity.this)
.setMessage(message)
.setPositiveButton("OK",okListener)
.setNegativeButton("Cancel",null)
.create()
.show();
}

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

17/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

The result are rational dialog will be shown when this permission is
requested for the first time and also be shown if user has ever
marked that permission as Never ask again. For the latter case,
onRequestPermissionsResult will be called with PERMISSION_DENIED

without any permission grant dialog.

Done !

Asking for multiple permissionsat


a time

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

18/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

There is definitely some feature that requires more than one


permission. You could request for multiple permissions at a time
with same method as above. Anyway don't forget to check the 'Never
ask again' case for every single permission as well.
Here isthe revised code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

finalprivateintREQUEST_CODE_ASK_MULTIPLE_PERMISSIONS=124;

privatevoidinsertDummyContactWrapper(){
List<String>permissionsNeeded=newArrayList<String>();

finalList<String>permissionsList=newArrayList<String>();
if(!addPermission(permissionsList,Manifest.permission.ACCESS_FINE_
permissionsNeeded.add("GPS");
if(!addPermission(permissionsList,Manifest.permission.READ_CONTACT
permissionsNeeded.add("ReadContacts");
if(!addPermission(permissionsList,Manifest.permission.WRITE_CONTAC
permissionsNeeded.add("WriteContacts");

if(permissionsList.size()>0){
if(permissionsNeeded.size()>0){
//NeedRationale
Stringmessage="Youneedtograntaccessto"+permission
for(inti=1;i<permissionsNeeded.size();i++)
message=message+","+permissionsNeeded.get(i);
showMessageOKCancel(message,
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
requestPermissions(permissionsList.toArray(
REQUEST_CODE_ASK_MULTIPLE_PERMISSION
}
});
return;
}
requestPermissions(permissionsList.toArray(newString[permission
REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
return;
}

insertDummyContact();
}

privatebooleanaddPermission(List<String>permissionsList,Stringpermi
if(checkSelfPermission(permission)!=PackageManager.PERMISSION_GRA
permissionsList.add(permission);
//CheckforRationaleOption
if(!shouldShowRequestPermissionRationale(permission))
returnfalse;
}

45

returntrue;

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

19/29

1/11/2016

45
46

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

returntrue;
}

When every single permission got its grant result, the result will be
sent to the same callback method, onRequestPermissionsResult . I
use HashMap to make source codelooks cleaner and more
readable.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

@Override
publicvoidonRequestPermissionsResult(intrequestCode,String[]permiss
switch(requestCode){
caseREQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
{
Map<String,Integer>perms=newHashMap<String,Integer>();
//Initial
perms.put(Manifest.permission.ACCESS_FINE_LOCATION,PackageM
perms.put(Manifest.permission.READ_CONTACTS,PackageManager.
perms.put(Manifest.permission.WRITE_CONTACTS,PackageManager
//Fillwithresults
for(inti=0;i<permissions.length;i++)
perms.put(permissions[i],grantResults[i]);
//CheckforACCESS_FINE_LOCATION
if(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)==P
&&perms.get(Manifest.permission.READ_CONTACTS)==P
&&perms.get(Manifest.permission.WRITE_CONTACTS)==
//AllPermissionsGranted
insertDummyContact();
}else{
//PermissionDenied
Toast.makeText(MainActivity.this,"SomePermissionisDe
.show();
}
}
break;
default:
super.onRequestPermissionsResult(requestCode,permissions,g
}
}

The condition is flexible. You have to set it by your own. In some


case, if even one permission is not granted, that feature will be just
simply disabled. But in some case, it will still work but with limited
feature. There is no suggestion from me. It is all byyour design.

Use Support Libraryto make code

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

20/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Use Support Libraryto make code


forward-compatible
Although the code above works perfectly on Android 6.0
Marshmallow. Unfortunate that it will crash on Android preMarshmallow since those functions called are added inAPI Level 23.
The straight way is you can check Build Version with code below.
1
2
3
4
5

if(Build.VERSION.SDK_INT>=23){
//Marshmallow+
}else{
//PreMarshmallow
}

But code will be even more complicated. So I suggest you to use


some help from Support Library v4 which is already prepared for
this thing. Replace those functions with these:
-ContextCompat.checkSelfPermission()
No matterapplication is run on M or not. This function will
correctly return PERMISSION_GRANTED if the permission is granted.
Otherwise PERMISSION_DENIED will be returned.
-ActivityCompat.requestPermissions()
If this function is called on pre-M,
OnRequestPermissionsResultCallback will be suddenly called with
correct PERMISSION_GRANTED or PERMISSION_DENIED result.
- ActivityCompat.shouldShowRequestPermissionRationale()

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

21/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

If this function is called on pre-M,it will always return false .


ALWAYSreplace Activity's checkSelfPermission ,
requestPermissions

and shouldShowRequestPermissionRationale with these functions


from Support Library v4.And your application will work perfectly
find on any Android version with same code logic. Please note that
these functions require some additional parameter: Context or
Activity. Nothing special to do, just pass what it wants correctly. Here
is what source code will look like.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

privatevoidinsertDummyContactWrapper(){
inthasWriteContactsPermission=ContextCompat.checkSelfPermission(M
Manifest.permission.WRITE_CONTACTS);
if(hasWriteContactsPermission!=PackageManager.PERMISSION_GRANTED)
if(!ActivityCompat.shouldShowRequestPermissionRationale(MainAct
Manifest.permission.WRITE_CONTACTS)){
showMessageOKCancel("YouneedtoallowaccesstoContacts"
newDialogInterface.OnClickListener(){
@Override
publicvoidonClick(DialogInterfacedialog,
ActivityCompat.requestPermissions(MainActivi
newString[]{Manifest.permission.WR
REQUEST_CODE_ASK_PERMISSIONS);
}
});
return;
}
ActivityCompat.requestPermissions(MainActivity.this,
newString[]{Manifest.permission.WRITE_CONTACTS},
REQUEST_CODE_ASK_PERMISSIONS);
return;
}
insertDummyContact();
}

Besides we are also able to call the last two methods in Fragment
with some help from Support Library v13 by calling

FragmentCompat.requestPermissions() and FragmentCompat.shouldShowReque

functions will do exactly the same as Activity's.

Shorten source code with 3rd Party

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

22/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

Shorten source code with 3rd Party


Library
You will notice that code is quite complicated. No surprise, there are
quite many of 3rd party libraries out there trying to solve this big
thing. I gave a try with quite a lot of them and finallyfound one that
satisfy me. It is hotchemi'sPermissionsDispatcher
(http://hotchemi.github.io/PermissionsDispatcher/).
What is does it exactly the same as I described above but just with
shorter and cleaner code. Surely with some trade-off with flexibility.
Please give it a try and see if it could be applied inyour application. If
it couldn't, you can go on the direct way which is also my choice right
now.

What will happen ifpermission is


revoked while application is
opened?
As mentioned above, a permission can be revoked anytime through
phone's Settings.

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

23/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

So what will happen if permission is revoked when application is


opened? I have already given it a try and found that application's
process is suddenly terminated. Everything inside application just
simply stopped (since it is already terminated ...). It sounds make
sense to me anyway since if OS allows the application to go on its
process, it may summon Freddy to mynightmare. I mean even
worsenightmare than currently is ...

Conclusion and Suggestion


I believe that you seethe big picture of this new permission system
quite clear right now. And I believe that you also see how big issue it
is.
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

24/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

However you have no choice. Runtime Permission is already used in


Android Marshmallow. We are at the point of no return. Only thing
we could do right now is to make our application fully support this
new permission system.
Good news is there are only few permission that requires Runtime
Permission flow. Most of the frequently-used permissions, for
example, INTERNET,are in Normal Permission
(https://developer.android.com/preview/features/runtimepermissions.html#normal) are automatically granted and you have
no need to do anything with them. In conclusion, there are just few
part of code that you need to modify.
There are two suggestions to you all:
1)Make Runtime Permission support an urgentissue
2) Don't set application's targetSdkVersion to 23 if your code is
not yet supported Runtime Permission. Especially when you
create a new project from Android Studio, don't forget to take a
look at build.gradle everytime for targetSdkVersion !
Talk about source code modification, I must admit that it is quite a
big thing. If code structure is not designed good enough, you may
need some serious reconstruction which will surely take some time.
Or at least I believe that source code need to be refactored for every
single application. Anyway like I said above, we have no choice ...
In the man time, since permission concept is turned upside down.
Right now if some permission is not granted, your application need
to still be able to work with limited feature. So I suggest you to list all

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

25/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

the feature that related to permission you requested. And write


down all the case possible, if permission A is granted but permission
B is denied, what will happen. Blah blah blah.
Good luck with your code refactoring. Markit as urgent in your to-do
list and start do it today so it will contains no problem on the day
Android M is publicly launched.
Hope you find this article helpful and Happy Coding !
More details are available here
(https://developer.android.com/preview/features/runtimepermissions.html).
Author: nuuneoi (Android GDE, CTO & CEO at The Cheese Factory)
A full-stack developer with more than 6 years experience on Android Application
Development and more than 12 years in Mobile Application Development
industry. Also has skill in Infrastucture, Service Side, Design, UI&UX, Hardware,
Optimization, Cooking, Photographing, Blogging, Training, Public Speaking and
do love to share things to people in the world!

Tweet
Like

209
Share 298peoplelikethis.

37Comments

Sortby Oldest

Addacomment...

NitinSethiBangalore,India
Nicearticle.Thanks.Youneedtoproofreadthearticlebetterasyoualways
endupwithanumberoftypos.
LikeReply

3Aug25,201510:05pmEdited

RodrigoGraaDeveloperatEVOKEIT
Thisisinsane...Aretheycrazy?
AndroidMshouldprompttheuser,nottheappdeveloper....
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

26/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

AndroidMshouldprompttheuser,nottheappdeveloper....
Awaytomakesureanappworks,willbetoaskforallthepermissionswhen
theappstarts,sincetheprocessisclosediftheuserschangesitwhilethe
applicationisopen...
LikeReply

2Aug26,20154:33am

DouglasDrumondAndroidDevelopmentAnalystatMovile
Thenyourisktheuserdenyingallofthem,sincetheydon'ttrustthe
appyetandhavenoideawhyitneedsthatpermission(unlessit's
obvious,likeacameraappaskingforcamerapermission).
LikeReplyAug27,201511:45pm

RodrigoGraaDeveloperatEVOKEIT
@DouglasDrumondOk....So,itshouldbetheOS(Android)askingfor
thepermissionwhenthecodecalledsomethingforthefirsttime.....
Thisway,ifacameraappsuddenlywantedtosendoneSMS,theuser
wouldnoticethepromptforthepermissionandprobablyuninstallthe
app...
LikeReply

1Aug28,20151:47amEdited

ViratSingh
Thankyouforthisblogpost!IthelpedmegetstartedwiththeAndroidM
permissions.
IwouldliketomentionthatshouldShowRequestPermissionRationale(...)returns
falsefor2reasonsnowwiththefinalAndroidMSDKupdate:
1.When"Don'taskagain"ischecked(asyoumentioned)
2.Ifthedevicepolicyprohibitstheappfromhavingthatpermission(returns
falseoninitialpermissionprompt)
Ithinkthe2ndreasonmaycausesomeissueswithyourcurrent
implementation.SinceasofthefinalAndroidMSDKupdate(update3,August
2015),shouldShowRequestPermissionRationale(...)alwaysreturnsfalseinitially
aswellaswhen"Don'taskagain"ischecked.
Hereisalinktothedocswiththeexplanation:... SeeMore
LikeReply

2Aug26,201511:07amEdited

DavidLaumaillier
IhopeallthisisforrootedphonesonlyotherwiseI'mintrouble.Didn't
understandmostofit.
LikeReplyAug26,20157:29pm

DouglasDrumondAndroidDevelopmentAnalystatMovile
Ifyou'renotadeveloper,don'tworry.Ifyou'readeveloperanddon't
getit,sorrytoinformyou,youneedtostudyalittlebit,thisisnotrocket
science.
LikeReply

1Aug27,201511:44pm

DavidLaumaillier
Wow,thanksforthatinsult.Sorryfortroublingyoursuperioritywithmy
comment.
http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

27/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

comment.
LikeReplyAug28,20152:05am

JiaxinJiWorksat
DavidLaumaillier!~
LikeReplyAug31,20151:12am
Show1morereplyinthisthread

Related

Retrofit 2.0: The biggest update yet on the best


HTTP Client Library for Android
(/blog/retrofit-2.0/en)
Posted on 6 Sep 2015 12:33

How to setup ACRA, an Android Application Crash


Tracking system, on your own host
Application Crash Reports on Android

(/blog/how-to-install-and-use-acra-android/en)
Posted on 1 Mar 2015 23:35

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

28/29

1/11/2016

EverythingeveryAndroidDevelopermustknowaboutnewAndroid'sRuntimePermission::TheCheeseFactory

(http://twitter.com/thecheesefact)

(http://facebook.com/inthecheesefactory)

(/blog/en/rss.xml)

Copyright The Cheese Factory Co.,Ltd. 2015

http://inthecheesefactory.com/blog/thingsyouneedtoknowaboutandroidmpermissiondeveloperedition/en

29/29

Das könnte Ihnen auch gefallen