您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關androidQ sd卡權限詳細使用說明,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。
默認情況下,如果應用以 Android Q 為目標平臺,則在訪問外部存儲設備中的文件時會進入過濾視圖。應用可以使用 Context.getExternalFilesDir() 將專用于自己的文件存儲在特定于自己的目錄中。
1. 臨時停用分區存儲行為:
以 Android 9(API 級別 28)或更低版本為目標平臺。
如果您以 Android Q 為目標平臺,請在應用的清單文件中將 requestLegacyExternalStorage 的值設為 true。
<manifest ... > <!-- This attribute is "false" by default on apps targeting Android Q. --> <application android:requestLegacyExternalStorage="true" ... > ... </application> </manifest>
2. 如何實現隔離存儲:
2.1 ApplicationInfo新增PRIVATE_FLAG_REQUEST_LEGACY_EXTERNAL_STORAGE標記
PackageParser.java:
if (sa.getBoolean( R.styleable.AndroidManifestApplication_requestLegacyExternalStorage, owner.applicationInfo.targetSdkVersion < Build.VERSION_CODES.Q)) { ai.privateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUEST_LEGACY_EXTERNAL_STORAGE; }
ApplicationInfo.java:
public boolean hasRequestedLegacyExternalStorage() { return (privateFlags & PRIVATE_FLAG_REQUEST_LEGACY_EXTERNAL_STORAGE) != 0; }
2.2 grantRuntimePermission()重新掛載視圖
apk啟動時默認掛載runtime/default視圖,grantRuntimePermission()時如果是READ_EXTERNAL_STORAGE或WRITE_EXTERNAL_STORAGE,則會獲取掛載模式重新掛載對應視圖。
PermissionManagerService.java:
private void grantRuntimePermission(String permName, String packageName, boolean overridePolicy, int callingUid, final int userId, PermissionCallback callback) { ...... if (READ_EXTERNAL_STORAGE.equals(permName) || WRITE_EXTERNAL_STORAGE.equals(permName)) { final long token = Binder.clearCallingIdentity(); try { if (mUserManagerInt.isUserInitialized(userId)) { StorageManagerInternal storageManagerInternal = LocalServices.getService( StorageManagerInternal.class); storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); } } finally { Binder.restoreCallingIdentity(token); } } }
獲取掛載模式這塊android10有修改,沒有設置Legacy標志的話,總是獲取default掛載模式,沒有讀寫權限。
android 10會設置屬性[persist.sys.isolated_storage]: [true],因此走到if(ENABLE_ISOLATED_STORAGE)中的getMountMode()。
public static boolean hasIsolatedStorage() { //[persist.sys.isolated_storage]: [true] //[sys.isolated_storage_snapshot]: [true] return SystemProperties.getBoolean("sys.isolated_storage_snapshot", SystemProperties.getBoolean("persist.sys.isolated_storage", true)); } private static final boolean ENABLE_ISOLATED_STORAGE = StorageManager.hasIsolatedStorage(); public int getExternalStorageMountMode(int uid, String packageName) { + //android 10新增邏輯 + if (ENABLE_ISOLATED_STORAGE) { + return getMountMode(uid, packageName); + } ...... int mountMode = Integer.MAX_VALUE; for (ExternalStorageMountPolicy policy : mPolicies) { final int policyMode = policy.getMountMode(uid, packageName); if (policyMode == Zygote.MOUNT_EXTERNAL_NONE) { return Zygote.MOUNT_EXTERNAL_NONE; } mountMode = Math.min(mountMode, policyMode); } if (mountMode == Integer.MAX_VALUE) { return Zygote.MOUNT_EXTERNAL_NONE; } return mountMode; }
正常模式下hasLegacy=false,走到if判斷的DEFAULT分支;legacy模式hasLegacy=true,與之前保持一致,有write權限就走到WRITE模式分支。
private int getMountModeInternal(int uid, String packageName) { try { ...... final boolean hasRead = StorageManager.checkPermissionAndCheckOp(mContext, false, 0, uid, packageName, READ_EXTERNAL_STORAGE, OP_READ_EXTERNAL_STORAGE); final boolean hasWrite = StorageManager.checkPermissionAndCheckOp(mContext, false, 0, uid, packageName, WRITE_EXTERNAL_STORAGE, OP_WRITE_EXTERNAL_STORAGE); ...... final boolean hasLegacy = mIAppOpsService.checkOperation(OP_LEGACY_STORAGE, uid, packageName) == MODE_ALLOWED; if (hasLegacy && hasWrite) { return Zygote.MOUNT_EXTERNAL_WRITE; } else if (hasLegacy && hasRead) { return Zygote.MOUNT_EXTERNAL_READ; } else { return Zygote.MOUNT_EXTERNAL_DEFAULT; } } catch (RemoteException e) { // Should not happen } return Zygote.MOUNT_EXTERNAL_NONE; }
2.3 Legacy Storage屬性對權限的影響
安裝apk時,就會根據requestLegacyExternalStorage屬性來對ops state進行設置,修改OP_LEGACY_STORAGE的默認狀態。
<manifest ... > <application android:requestLegacyExternalStorage="true" ... > </application> </manifest> //Q 正常模式 LEGACY_STORAGE: mode=ignore //Q legacy模式 LEGACY_STORAGE: mode=allow
PermissionPolicyService啟動時首先進行權限變化監聽:
public void onStart() { permManagerInternal.addOnRuntimePermissionStateChangedListener( this::synchronizePackagePermissionsAndAppOpsAsyncForUser); } private void synchronizePackagePermissionsAndAppOpsAsyncForUser(@NonNull String packageName, @UserIdInt int changedUserId) { if (isStarted(changedUserId)) { synchronized (mLock) { if (mIsPackageSyncsScheduled.add(new Pair<>(packageName, changedUserId))) { FgThread.getHandler().sendMessage(PooledLambda.obtainMessage( PermissionPolicyService ::synchronizePackagePermissionsAndAppOpsForUser, this, packageName, changedUserId)); } ...... } } }
APK安裝時,會根據requestLegacyExternalStorage屬性來通知storage權限變化,調用關系如下:
//調用關系: 1.PackageManagerService.java: installPackagesLI() commitPackagesLocked() updateSettingsLI() updateSettingsInternalLI() 2.PermissionManagerService.java: mPermissionManager.updatePermissions() restorePermissionState() //關鍵代碼: private void restorePermissionState(@NonNull PackageParser.Package pkg, boolean replace, @Nullable String packageOfInterest, @Nullable PermissionCallback callback) { ...... //判斷requestLegacyExternalStorage屬性 updatedUserIds = checkIfLegacyStorageOpsNeedToBeUpdated(pkg, replace, updatedUserIds); ...... for (int userId : updatedUserIds) { notifyRuntimePermissionStateChanged(pkg.packageName, userId); } }
最終調用到PermissionPolicyService的監聽函數synchronizePackagePermissionsAndAppOpsForUser(),進行默認權限獲取和設置。
當apk安裝時,聲明了requestLegacyExternalStorage="true"屬性,并且聲明了READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE,那么addOpIfRestricted()就會將LEGACY_STORAGE設置為allow模式。
//調用關系: synchronizePackagePermissionsAndAppOpsForUser(): synchroniser.addPackage() addOpIfRestricted()//LEGACY_STORAGE加入到mOpsToAllow synchroniser.syncPackages() setUidModeAllowed() setUidMode()//設置LEGACY_STORAGE為allow //關鍵代碼: private void addOpIfRestricted(@NonNull PermissionInfo permissionInfo, @NonNull PackageInfo pkg) { ...... //forPermission()會根據requestLegacyExternalStorage的值進行返回 final SoftRestrictedPermissionPolicy policy = SoftRestrictedPermissionPolicy.forPermission(mContext, pkg.applicationInfo, mContext.getUser(), permission); final int op = policy.resolveAppOp(); if (op != OP_NONE) { switch (policy.getDesiredOpMode()) { case MODE_DEFAULT: mOpsToDefault.add(new OpToChange(uid, pkg.packageName, op)); break; case MODE_ALLOWED: //在聲明READ_EXTERNAL_STORAGE權限下,會將LEGACY_STORAGE加入到mOpsToAllow if (policy.shouldSetAppOpIfNotDefault()) { mOpsToAllow.add(new OpToChange(uid, pkg.packageName, op)); } else { mOpsToAllowIfDefault.add( new OpToChange(uid, pkg.packageName, op)); } break; ...... } public static @NonNull SoftRestrictedPermissionPolicy forPermission(@NonNull Context context, @Nullable ApplicationInfo appInfo, @Nullable UserHandle user, @NonNull String permission) { switch (permission) { case READ_EXTERNAL_STORAGE: { if (appInfo != null) { boolean hasAnyRequestedLegacyExternalStorage = appInfo.hasRequestedLegacyExternalStorage(); hasRequestedLegacyExternalStorage = hasAnyRequestedLegacyExternalStorage; } return new SoftRestrictedPermissionPolicy() { @Override public int getDesiredOpMode() { if (applyRestriction) { return MODE_DEFAULT; } else if (hasRequestedLegacyExternalStorage) { //聲明了requestLegacyExternalStorage就返回allow return MODE_ALLOWED; } else { return MODE_IGNORED; } } @Override public boolean shouldSetAppOpIfNotDefault() { return getDesiredOpMode() != MODE_IGNORED; } }; }
3. sdcard路徑權限說明:
/data/media on /mnt/runtime/read/emulated type sdcardfs (rw,nosuid,nodev,noexec,noatime,fsuid=1023,fsgid=1023,gid=9997,multiuser,mask=23,derive_gid,default_normal)
/data/media on /mnt/runtime/write/emulated type sdcardfs (rw,nosuid,nodev,noexec,noatime,fsuid=1023,fsgid=1023,gid=9997,multiuser,mask=7,derive_gid,default_normal)
/mnt/runtime/default:
drwxrwx--x 3 root sdcard_rw 4096 2018-12-18 03:41 Android drwxrwx--x 3 root sdcard_rw 4096 2018-12-18 06:11 DCIM
/mnt/runtime/read:
drwxr-x--- 3 root everybody 4096 2018-12-18 03:41 Android drwxr-x--- 3 root everybody 4096 2018-12-18 06:11 DCIM
/mnt/runtime/write:
drwxrwx--- 3 root everybody 4096 2018-12-18 03:41 Android drwxrwx--- 3 root everybody 4096 2018-12-18 06:11 DCIM
/sdcard/Android/data:
drwxrwx--- 4 u0_a64 everybody 4096 2018-12-18 06:11 com.android.camera2 drwxrwx--- 3 u0_a15 everybody 4096 2018-12-18 03:41 com.google.android.gms drwxrwx--- 4 u0_a84 everybody 4096 2018-12-18 03:41 com.google.android.youtube
4. sdcard文件存儲示例:
4.1 getExternalFilesDir()隨卸載而刪除
///storage/emulated/0/Android/data/com.xx.xx/files File file = File(context.getExternalFilesDir(null), "test.txt");
4.2 媒體文件
媒體文件使用MediaStore操作,卸載后不會刪除。
訪問其他應用生成的照片、視頻、音頻,需要READ_EXTERNAL_STORAGE權限。
4.3 存儲訪問框架(SAF)
訪問其他應用創建的文件,例如"Download"目錄,必須使用存儲訪問框架,用戶通過框架選擇特定文件。
4.4 照片中的位置信息
需要ACCESS_MEDIA_LOCATION權限,才能獲取元數據中的位置信息。
<permission android:name="android.permission.ACCESS_MEDIA_LOCATION" android:permissionGroup="android.permission-group.UNDEFINED" android:label="@string/permlab_mediaLocation" android:description="@string/permdesc_mediaLocation" android:protectionLevel="dangerous" />
關于androidQ sd卡權限詳細使用說明就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。