簡體   English   中英

Android 6 Marshmallow權限無法正常工作

[英]Android 6 Marshmallow permissions not working properly

我試圖通過多次權限檢查訪問Android 6 Marshmallow中的所有聯系人和所有者電子郵件ID,但在我的應用中,有時它會因SecurityException而崩潰,有時它會顯示權限請求,當我允許時,它不會觸發讀取聯系人直到我重啟我的應用。

我在代碼中遺漏了什么嗎?

  public static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            if(checkAndRequestPermissions()) {
                // carry on the normal flow, as the case of  permissions  granted.
     try {
                    Account[] accounts = AccountManager.get(getApplicationContext()).getAccountsByType("com.google");
                    for (Account account : accounts) {
                        String emailid = account.name;
                        Log.e("account", emailid);
                    }
                } catch (Exception e) {
                    Log.e("Exception", "Exception:" + e);
                }
                ContentResolver cr = getApplicationContext().getContentResolver(); //Activity/Application android.content.Context
                Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
                if (cursor.moveToFirst()) {
                    do {
                        String contactid = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                        if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{contactid}, null);
                            while (pCur.moveToNext()) {
                                String contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                                String contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                alContacts.add(contactNumber);
                                alName.add(contactName);
                                Log.e("Contact Name", contactName);
                                Log.e("Contact Number", contactNumber);
                                break;
                            }
                            pCur.close();
                        }

                    } while (cursor.moveToNext());
                }
              }
            }
        }

        private  boolean checkAndRequestPermissions() {
            int permissionSendMessage = ContextCompat.checkSelfPermission(this,
                    Manifest.permission.SEND_SMS);
            int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
            List<String> listPermissionsNeeded = new ArrayList<>();
            if (locationPermission != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (permissionSendMessage != PackageManager.PERMISSION_GRANTED) {
                listPermissionsNeeded.add(Manifest.permission.SEND_SMS);
            }
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]),REQUEST_ID_MULTIPLE_PERMISSIONS);
                return false;
            }
            return true;
        }
         @Override
            public void onRequestPermissionsResult(int requestCode,
                                                   String permissions[], int[] grantResults) {
                Log.d(TAG, "Permission callback called-------");
                switch (requestCode) {
                    case REQUEST_ID_MULTIPLE_PERMISSIONS: {

                        Map<String, Integer> perms = new HashMap<>();
                        // Initialize the map with both permissions
                        perms.put(Manifest.permission.SEND_SMS, PackageManager.PERMISSION_GRANTED);
                        perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                        // Fill with actual results from user
                        if (grantResults.length > 0) {
                            for (int i = 0; i < permissions.length; i++)
                                perms.put(permissions[i], grantResults[i]);
                            // Check for both permissions
                            if (perms.get(Manifest.permission.SEND_SMS) == PackageManager.PERMISSION_GRANTED
                                    && perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                                Log.d(TAG, "sms & location services permission granted");
                                // process the normal flow
                                //else any one or both the permissions are not granted
                            } else {
                                    Log.d(TAG, "Some permissions are not granted ask again ");
                                    //permission is denied (this is the first time, when "never ask again" is not checked) so ask again explaining the usage of permission
        //                        // shouldShowRequestPermissionRationale will return true
                                    //show the dialog or snackbar saying its necessary and try again otherwise proceed with setup.
                                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                                        showDialogOK("SMS and Location Services Permission required for this app",
                                                new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        switch (which) {
                                                            case DialogInterface.BUTTON_POSITIVE:
                                                                checkAndRequestPermissions();
                                                                break;
                                                            case DialogInterface.BUTTON_NEGATIVE:
                                                                // proceed with logic by disabling the related features or quit the app.
                                                                break;
                                                        }
                                                    }
                                                });
                                    }
                                    //permission is denied (and never ask again is  checked)
                                    //shouldShowRequestPermissionRationale will return false
                                    else {
                                        Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG)
                                                .show();
            //                            //proceed with logic by disabling the related features or quit the app.
                                    }
                            }
                        }
                    }
                }

            }

            private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
                new AlertDialog.Builder(this)
                        .setMessage(message)
                        .setPositiveButton("OK", okListener)
                        .setNegativeButton("Cancel", okListener)
                        .create()
                        .show();
            }

用以下方法替換checkAndRequestPermissions()方法。

private  boolean checkAndRequestPermissions() {
      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {  
    if(this.checkSelfPermission(permission.SEND_SMS)== PackageManager.PERMISSION_GRANTED && this.checkSelfPermission(permission.ACCESS_FINE_LOCATION)== PackageManager.PERMISSION_GRANTED){
                return true;
            }else{
                if(shouldShowRequestPermissionRationale(Manifest.permission.SEND_SMS)){
                    Toast.makeText(MainActivity.this,"Your Permissions is required to send msg .....",Toast.LENGTH_LONG).show();
                    return false;
                }
                if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)){
                    Toast.makeText(MainActivity.this,"Your Permissions is required to get your current location .....",Toast.LENGTH_LONG).show();
                    return false;
                }
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.permission.SEND_SMS}, REQUEST_ID_MULTIPLE_PERMISSIONS);
            return false;
            }
    }else{
            return true;
        }
        return false;

    }

試試這個簡單的android權限庫。 它使開發人員的生活更加輕松

只需在gradle中包含以下依賴項即可

dependencies {
    compile 'com.vistrav:ask:1.2'
}

並在您的活動中使用以下代碼段來請求許可。

Ask.on(context)
                .forPermissions(Manifest.permission.ACCESS_COARSE_LOCATION
                        , Manifest.permission.WRITE_EXTERNAL_STORAGE) //one or more permissions
                .withRationales("Location permission need for map to work properly", 
                        "In order to save file you will need to grant storage permission") //optional
                .when(new Ask.Permission() {
                    @Override
                    public void granted(List<String> permissions) {
                        Log.i(TAG, "granted :: " + permissions);
                    }

                    @Override
                    public void denied(List<String> permissions) {
                        Log.i(TAG, "denied :: " + permissions);
                    }
                }).go();

這就是你所需要的。

暫無
暫無

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

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