Android 權(quán)限管理

權(quán)限分類

  • Normal permissions

    只需要在AndroidManifest.xml 中聲明,如INTERNET骇径,WAKE_LOCK等

  • Signature permissions

    申請(qǐng)?jiān)摍?quán)限的應(yīng)用和定義該權(quán)限的應(yīng)用有相同簽名時(shí),這個(gè)權(quán)限才會(huì)被授予,一些Signature permissions不能被三方應(yīng)用使用

  • Dangerous permissions

    需要申請(qǐng)運(yùn)行時(shí)權(quán)限

  • Special permissions
    如SYSTEM_ALERT_WINDOW需要應(yīng)用發(fā)送Settings.ACTION_MANAGE_OVERLAY_PERMISSION intent去提示用戶是否開(kāi)啟該權(quán)限

權(quán)限列表可以參考官網(wǎng):
https://developer.android.google.cn/guide/topics/permissions/overview?hl=en

代碼中的權(quán)限列表:
frameworks/base/data/etc/platform.xml

權(quán)限類型定義protectionLevel:
frameworks/base/core/res/AndroidManifest.xml

運(yùn)行時(shí)權(quán)限申請(qǐng)方法

AndroidMenifest.xml 中添加

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

代碼中添加:

        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                // Show an expanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.

            } else {

                // No explanation needed, we can request the permission.

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_SDCARD);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_SDCARD: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            ... ...
                } else {
                    ... ...
                }
                return;
            }
        }
    }

查看應(yīng)用是否有運(yùn)行時(shí)權(quán)限:

adb shell dumpsys package + 包名
Packages:
  Package [com.example.hellojni2] (11f567c):
    userId=10127
    pkg=Package{714cb29 com.example.hellojni2}
    ... ...

    requested permissions:
      android.permission.WRITE_SETTINGS
      android.permission.READ_EXTERNAL_STORAGE
      android.permission.WRITE_EXTERNAL_STORAGE
    User 0: ceDataInode=-4294761261 installed=true hidden=false suspended=false stopped=false notLaunched=false enabled=0 instant=false virtual=false
      runtime permissions:
        android.permission.READ_EXTERNAL_STORAGE: granted=true
        android.permission.WRITE_EXTERNAL_STORAGE: granted=true

查看應(yīng)用進(jìn)程是否有某個(gè)權(quán)限痢毒,比如進(jìn)程mediacodec澜建,pid: 564是否有sdcard_rw權(quán)限

A3A_10_4G:/ $ cd proc/564
A3A_10_4G:/proc/564 $ cat status
Name:   omx@1.0-service
State:  S (sleeping)
Tgid:   564
Ngid:   0
Pid:    564
PPid:   1
TracerPid:  0
Uid:    1046    1046    1046    1046
Gid:    1006    1006    1006    1006
FDSize: 256
Groups: 1000 1005 1013 1015 1023 1026 1028 1031 3001 3002 3003 3007 


id sdcard_rw

A3A_10_4G:/ $ id sdcard_rw                                                     
uid=1015(sdcard_rw) gid=1015(sdcard_rw) groups=1015(sdcard_rw), context=u:r:shell:s0


可以看到有1015權(quán)限,即SDCard讀寫(xiě)錯(cuò)誤

運(yùn)行時(shí)權(quán)限申請(qǐng)流程

1. 顯示權(quán)限申請(qǐng)Dialog

frameworks/support/compat/src/main/java/androidx/core/app/ActivityCompat.java

      public static void requestPermissions(final @NonNull Activity activity,
              final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode) {
            ... ...
  
          if (Build.VERSION.SDK_INT >= 23) {
             
              activity.requestPermissions(permissions, requestCode);
          } 
            ... ...
      }

打開(kāi)全透明GrantPermissionsActivity

      public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
          ... ...
          //沒(méi)有申請(qǐng)過(guò)權(quán)限彈出權(quán)限申請(qǐng)dialog
          Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions);
          startActivityForResult(REQUEST_PERMISSIONS_WHO_PREFIX, intent, requestCode, null);
          mHasCurrentPermissionsRequest = true;
      }

GrantPermissionsActivity實(shí)現(xiàn)接口GrantPermissionsViewHandler.ResultListener向挖,用戶點(diǎn)擊允許添加權(quán)限時(shí),回調(diào) onPermissionGrantResult

      @Override
      public void onPermissionGrantResult(String name, boolean granted, boolean doNotAskAgain) {

            ... ...  
          GroupState groupState = mRequestGrantPermissionGroups.get(name);
          if (groupState != null && groupState.mGroup != null) {
              if (granted) {
                  //如果允許將整個(gè)權(quán)限組權(quán)限設(shè)為STATE_ALLOWED
                  groupState.mGroup.grantRuntimePermissions(doNotAskAgain,
                          groupState.affectedPermissions);
                  groupState.mState = GroupState.STATE_ALLOWED;
              } else {
               ... ... 
      }

2. 最終調(diào)用到PMS的grantRuntimePermission更新權(quán)限

frameworks/base/services/core/java/com/android/server/pm/permission/PermissionManagerService.java

private void grantRuntimePermission(String permName, String packageName, boolean overridePolicy,
              int callingUid, final int userId, PermissionCallback callback) {
  
          mContext.enforceCallingOrSelfPermission(
                  android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS,
                  "grantRuntimePermission");
  
          enforceCrossUserPermission(callingUid, userId,
                  true,  // requireFullPermission
                  true,  // checkShell
                  false, // requirePermissionWhenSameUser
                  "grantRuntimePermission");
  
          final PackageParser.Package pkg = mPackageManagerInt.getPackage(packageName);
          if (pkg == null || pkg.mExtras == null) {
              throw new IllegalArgumentException("Unknown package: " + packageName);
          }
          final BasePermission bp;
          synchronized(mLock) {
              bp = mSettings.getPermissionLocked(permName);
          }
       ... ...
          //檢查AndroidManifest.xml中是否有聲明過(guò)權(quán)限炕舵,如果沒(méi)有拋出SecurityException異常
          bp.enforceDeclaredUsedAndRuntimeOrDevelopment(pkg);
  
  
          final int uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
  
          final PackageSetting ps = (PackageSetting) pkg.mExtras;
          final PermissionsState permissionsState = ps.getPermissionsState();
      『沃//省略一些對(duì)版本和權(quán)限類型檢查
       ... ...
  
          final int result = permissionsState.grantRuntimePermission(bp, userId);
          switch (result) {
              case PermissionsState.PERMISSION_OPERATION_FAILURE: {
                  return;
              }
  
              case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
                  if (callback != null) {
                      callback.onGidsChanged(UserHandle.getAppId(pkg.applicationInfo.uid), userId);
                  }
              }
              break;
          }
  

              //存在runtime-permissions.xml中
          if (callback != null) {
              callback.onPermissionGranted(uid, userId);
          }
       ... ...
      }

3.權(quán)限信息存儲(chǔ)

frameworks/base/services/core/java/com/android/server/pm/permission/PermissionsState.java

      private int grantPermission(BasePermission permission, int userId) {
          if (hasPermission(permission.getName(), userId)) {
              return PERMISSION_OPERATION_FAILURE;
          }
  
          final boolean hasGids = !ArrayUtils.isEmpty(permission.computeGids(userId));
          final int[] oldGids = hasGids ? computeGids(userId) : NO_GIDS;
  
          PermissionData permissionData = ensurePermissionData(permission);
          得到權(quán)限信息后,將權(quán)限和userid存在一個(gè) SparseArray數(shù)據(jù)結(jié)構(gòu)中咽筋,用于查看對(duì)應(yīng)權(quán)限是否申請(qǐng)
          if (!permissionData.grant(userId)) {
              return PERMISSION_OPERATION_FAILURE;
          }
  
          if (hasGids) {
              final int[] newGids = computeGids(userId);
              if (oldGids.length != newGids.length) {
                  return PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED;
              }
          }
  
          return PERMISSION_OPERATION_SUCCESS;
      }

 private PermissionCallback mPermissionCallback = new PermissionCallback() {

        @Override
        public void onPermissionGranted(int uid, int userId) {
            mOnPermissionChangeListeners.onPermissionsChanged(uid);

            // 應(yīng)用權(quán)限存儲(chǔ)在data/system/user/0/runtime-permissions.xml 手機(jī)啟動(dòng)時(shí)由PackageManagerService讀取
            synchronized (mPackages) {
                mSettings.writeRuntimePermissionsForUserLPr(userId, false);
            }
        }
        ... ...
    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末溶推,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子奸攻,更是在濱河造成了極大的恐慌蒜危,老刑警劉巖,帶你破解...
    沈念sama閱讀 206,968評(píng)論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件睹耐,死亡現(xiàn)場(chǎng)離奇詭異舰褪,居然都是意外死亡锄俄,警方通過(guò)查閱死者的電腦和手機(jī)惠奸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評(píng)論 2 382
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)兄墅,“玉大人,你說(shuō)我怎么就攤上這事晃酒”砝危” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 153,220評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵贝次,是天一觀的道長(zhǎng)崔兴。 經(jīng)常有香客問(wèn)我,道長(zhǎng)蛔翅,這世上最難降的妖魔是什么敲茄? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 55,416評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮山析,結(jié)果婚禮上堰燎,老公的妹妹穿的比我還像新娘。我一直安慰自己笋轨,他們只是感情好秆剪,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,425評(píng)論 5 374
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著爵政,像睡著了一般仅讽。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上钾挟,一...
    開(kāi)封第一講書(shū)人閱讀 49,144評(píng)論 1 285
  • 那天洁灵,我揣著相機(jī)與錄音,去河邊找鬼掺出。 笑死徽千,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蛛砰。 我是一名探鬼主播,決...
    沈念sama閱讀 38,432評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼黍衙,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼泥畅!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起琅翻,我...
    開(kāi)封第一講書(shū)人閱讀 37,088評(píng)論 0 261
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤位仁,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后方椎,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體聂抢,經(jīng)...
    沈念sama閱讀 43,586評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,028評(píng)論 2 325
  • 正文 我和宋清朗相戀三年棠众,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了琳疏。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片有决。...
    茶點(diǎn)故事閱讀 38,137評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖空盼,靈堂內(nèi)的尸體忽然破棺而出书幕,到底是詐尸還是另有隱情,我是刑警寧澤揽趾,帶...
    沈念sama閱讀 33,783評(píng)論 4 324
  • 正文 年R本政府宣布台汇,位于F島的核電站,受9級(jí)特大地震影響篱瞎,放射性物質(zhì)發(fā)生泄漏苟呐。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,343評(píng)論 3 307
  • 文/蒙蒙 一俐筋、第九天 我趴在偏房一處隱蔽的房頂上張望牵素。 院中可真熱鬧,春花似錦校哎、人聲如沸两波。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,333評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)腰奋。三九已至,卻和暖如春抱怔,著一層夾襖步出監(jiān)牢的瞬間劣坊,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,559評(píng)論 1 262
  • 我被黑心中介騙來(lái)泰國(guó)打工屈留, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留局冰,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,595評(píng)論 2 355
  • 正文 我出身青樓灌危,卻偏偏與公主長(zhǎng)得像康二,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子勇蝙,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,901評(píng)論 2 345

推薦閱讀更多精彩內(nèi)容