Code:
void clearCache() {
if (mClearCacheObserver == null) {
mClearCacheObserver = new CachePackageDataObserver();
}
From Android M -> CLEAR_APP_CACHE, Protection level: system|signature
Android 6.0 does not change the behavior of normal permissions (all non-dangerous permissions including normal, system, and signature permissions).
So it is not possible to ask for that permission in runtime. To be more precise
A signature|system permission, meaning that it can only be held by apps that are signed with the firmware's signing key or are installed on the system partition (e.g., by a rooted device user). From this stackoverflow Q/A.
Docs: https://source.android.com/devices/tech/config/runtime_perms.html#affected-permissions
Prior to Android 6.0, CLEAR_APP_CACHE had a protectionLevel of dangerous, so ordinary SDK apps could request it in the manifest.
As of Android 6.0, CLEAR_APP_CACHE has a protectionLevel of signature|privileged. Ordinary Android apps cannot hold this permission. You can only hold this permission if your app is signed with the firmware's signing key or you are installed on the privileged system partition.
Add Permission in AndroidManifest.xml
<permission android:name="android.permission.CLEAR_APP_CACHE"/>
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"/>
Make a Constant for Request Code.
Constants.java
public static final int REQUEST_CODE_FOR_PERMISSION = 501;
Request Permission :-
public static void requestPermissionForClearCache(Activity activity) {
if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.CLEAR_APP_CACHE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CLEAR_APP_CACHE)) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CLEAR_APP_CACHE}, Constatnts.REQUEST_CODE_FOR_PERMISSION);
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.CLEAR_APP_CACHE}, Constatnts.REQUEST_CODE_FOR_PERMISSION);
}
}
}
Override Below method in Fragment.
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == Constatnts.REQUEST_CODE_FOR_PERMISSION && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted successfully
} else {
// permission was NOT granted successfully
}
}