簡體   English   中英

我應該從哪個 api 請求權限?

[英]From which api should i ask permissions?

嘿,我正在嘗試請求存儲訪問權限,但我注意到在我的另一部裝有 android 5.0 的手機中,權限請求使應用程序崩潰。 我應該怎么做才能在不使此 android 版本中的應用程序崩潰的情況下獲得許可,我應該從哪個 android 版本執行此操作?

這是請求許可的代碼:

  int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 0;
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (shouldShowRequestPermissionRationale(
            Manifest.permission.READ_EXTERNAL_STORAGE)) {
        // Explain to the user why we need to read the contacts
    }

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
    // app-defined int constant that should be quite unique

    return;
}

動態權限需要 API 23 或更高版本,因此您可以將代碼封裝在有條件檢查正在運行的 API 版本中。

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 0;
    if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
        != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if(shouldShowRequestPermissionRationale(
            Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // Explain to the user why we need to read the contacts
        }

        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

        // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
        // app-defined int constant that should be quite unique

        return;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM