SecurityException:Android上的权限拒绝

时间:2015-12-03 13:54:30

标签: android android-manifest

我正在尝试从我的Android设备上读取短信。我已经编写了所需的代码,但我得到了权限拒绝错误。我在Android Manifest文件中添加了User-Permission(READ-SMS)。我将失去权限错误,我将其打印在Log.i(else block)

我的代码如下:

public ArrayList fetchInbox()
{
    ArrayList sms = new ArrayList();

    Uri uriSms = Uri.parse("content://sms/inbox");

    Cursor cursor = getContentResolver().query(uriSms, new String[]{"_id", "address", "date", "body"},null,null,null);

    if(ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {            Cursor cursor = cr.query(uriSms, new String[]{"_id", "address", "date", "body", "read"}, "address = '+2345679'", null, null);

      getSmsLogs(cursor, MainActivity.this);
        Log.i("Hello", String.valueOf(cursor));

        cursor.moveToFirst();
        while (cursor.moveToNext()) {
            String address = cursor.getString(1);
            String body = cursor.getString(3);

            Log.i("Hello","======> Mobile number => " + address);
            Log.i("Hello","=====> SMS Text => " + body);

            sms.add("Address=> " + address + "n SMS => " + body);
        }
    }
    else
    {
        Log.i("Hello", "Out of permission");
    }
    return sms;

}

错误消息:

 java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider uri content://sms/inbox from pid=28309, uid=10060 requires android.permission.READ_SMS, or grantUriPermission()

TargetSdkVersion : 23

谢谢。

1 个答案:

答案 0 :(得分:1)

使用此

if(ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED) {
...
...
 }

如果没有权限,则短信代码使用此

ActivityCompat.requestPermissions(UnlockActivity.this, new String[]{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);

希望它能运作