Android运行时权限已被授予但仍被拒绝

时间:2017-06-27 09:38:38

标签: android sms runtime-permissions

我正在尝试编写发送短信的应用。检查我是否具有所需权限时,它返回true但仍然与SecurityException崩溃。

按下按钮时

private void startAutoMsg() {
    Log.d("Starting Auto Msg");
    //FIXME: Start proper loop
    if (canSendSms()) {
        sendMessage();
        mAutoMsgButton.setBackgroundColor(Color.GREEN);
    }
}

我使用以下功能确定我是否拥有适当的权限

private boolean canSendSms() {
    if ((ContextCompat.checkSelfPermission(mContext, Manifest.permission.SEND_SMS)
            == PackageManager.PERMISSION_GRANTED)) {
        Log.d("Permission granted");
        return true;
    } else {
        Log.d("Permission denied");
        ActivityCompat.requestPermissions(
                mActivity, new String[]{Manifest.permission.SEND_SMS}, 101);
        return false;
    }
}

上面的代码返回true,因此正在尝试使用此

发送SMS
private void sendMessage() {
    Log.d("sending message");
    PendingIntent sentPI = PendingIntent.getBroadcast(
            mContext, 0, new Intent(Constants.ACTION_SMS_SENT), 0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(
            mContext, 0, new Intent(Constants.ACTION_SMS_DELIVERED), 0);
    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            mSmsManager.sendTextMessage("mNumber", null, mText, sentPI, deliveredPI);
        }
    });
    thread.run();
}

在我的清单中:

<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.RECEIVE_MMS" />

从崩溃中记录

D/SmsApp: TelephonyFragment: canSendSms(533): Permission granted
D/SmsApp: TelephonyFragment: sendMessage(222): sending message
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.android.phone, PID: 16736
                  java.lang.SecurityException: Sending SMS message: uid 1001 does not have android.permission.SEND_SMS.
                      at android.app.ContextImpl.enforce(ContextImpl.java:1727)
                      at android.app.ContextImpl.enforceCallingPermission(ContextImpl.java:1749)
                      at android.content.ContextWrapper.enforceCallingPermission(ContextWrapper.java:750)
                      at android.content.ContextWrapper.enforceCallingPermission(ContextWrapper.java:750)
                      at com.android.internal.telephony.IccSmsInterfaceManager.sendText(IccSmsInterfaceManager.java:410)
                      at com.android.internal.telephony.UiccSmsController.sendTextForSubscriber(UiccSmsController.java:136)
                      at android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:366)
                      at android.telephony.SmsManager.sendTextMessage(SmsManager.java:349)
                      at com.rawinc.smsapp.ui.telephony.TelephonyFragment$2.run(TelephonyFragment.java:230)
                      at java.lang.Thread.run(Thread.java:764)
                      at com.rawinc.smsapp.ui.telephony.TelephonyFragment.sendMessage(TelephonyFragment.java:233)
                      at com.rawinc.smsapp.ui.telephony.TelephonyFragment.startAutoMsg(TelephonyFragment.java:517)
                      at com.rawinc.smsapp.ui.telephony.TelephonyFragment.toggleAutoMsg(TelephonyFragment.java:507)
                      at com.rawinc.smsapp.ui.telephony.TelephonyFragment.lambda$-com_rawinc_smsapp_ui_telephony_TelephonyFragment_11555(TelephonyFragment.java:359)
                      at com.rawinc.smsapp.ui.telephony.-$Lambda$uKVldJdEkN_fZa3QWm3EZHDa2r8$2.$m$0(Unknown Source:4)
                      at com.rawinc.smsapp.ui.telephony.-$Lambda$uKVldJdEkN_fZa3QWm3EZHDa2r8$2.onClick(Unknown Source:0)
                      at android.view.View.performClick(View.java:6178)
                      at android.view.View$PerformClick.run(View.java:24416)
                      at android.os.Handler.handleCallback(Handler.java:769)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:255)
                      at android.app.ActivityThread.main(ActivityThread.java:6555)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

6 个答案:

答案 0 :(得分:0)

您需要处理onRequestPermissionResult

@Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0]== PackageManager.PERMISSION_GRANTED){
            Log.v("======>","Permission: "+permissions[0]+ "was "+grantResults[0]);
            //your task
        }
    }

并检查版本

if (Build.VERSION.SDK_INT >= 23) {
            if (checkSelfPermission(android.Manifest.permission.SEND_SMS)
                    == PackageManager.PERMISSION_GRANTED) {
                Log.v("======>","Permission is granted");
                return true;
            } else {

                Log.v("======>","Permission is revoked");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, 1);
                return false;
            }
        }
        else { //permission is automatically granted on sdk<23 upon installation
            Log.v("======>","Permission is granted");
            return true;
        }

并发送消息使用

private void sendMessage() {
        try {
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, "TXt", null, null);
            Toast.makeText(getApplicationContext(), "Message Sent",
                    Toast.LENGTH_LONG).show();
        } catch (Exception ex) {
            Toast.makeText(getApplicationContext(),ex.getMessage().toString(),
                    Toast.LENGTH_LONG).show();
            ex.printStackTrace();
        }
    }

答案 1 :(得分:0)

覆盖onRequestPermissionsResult方法

 @Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {

switch (requestCode) {
        case MY_PERMISSIONS_REQUEST: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the

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

                    //do whatever u want to do
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
            }
            return;
        }

        // other 'case' lines to check for other
        // permissions this app might request
    }

 }

答案 2 :(得分:0)

在需要位置时检查权限

if ((ContextCompat.checkSelfPermission(LoginActivity.this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED)) {
            requestPermissions(new String[]{Manifest.permission.SEND_SMS},
                    101);
        }

此行添加了您的活动

@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_CODE:
                if (grantResults.length <= 0 || grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }

答案 3 :(得分:0)

请这样做:

在您的应用中创建此类:

import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;


public abstract class RuntimePermissionsActivity extends AppCompatActivity
{


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        for (int permission : grantResults)
        {
            permissionCheck = permissionCheck + permission;
        }
        if ((grantResults.length > 0) && permissionCheck == PackageManager.PERMISSION_GRANTED)
        {
            onPermissionsGranted(requestCode);
        }
        else
        {
            onPermissionsDeny(requestCode);
        }
    }

    public void requestAppPermissions(final String[] requestedPermissions, final int requestCode)
    {
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        boolean shouldShowRequestPermissionRationale = false;
        for (String permission : requestedPermissions)
        {
            permissionCheck = permissionCheck + ContextCompat.checkSelfPermission(this, permission);
            shouldShowRequestPermissionRationale = shouldShowRequestPermissionRationale || ActivityCompat.shouldShowRequestPermissionRationale(this, permission);
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this, requestedPermissions, requestCode);
        }
        else
        {
            onPermissionsGranted(requestCode);
        }
    }

    public abstract void onPermissionsGranted(int requestCode);
    public abstract void onPermissionsDeny(int requestCode);

}

接下来在你的MainActivity(或任何Activity)中,你Shoulde从这个类扩展如下:

public class Main_Activity extends RuntimePermissionsActivity

在您的活动中覆盖此方法:

@Override
public void onPermissionsGranted(int requestCode) {

}

@Override
public void onPermissionsDeny(int requestCode) {

}

在决赛中:使用此代码检查Permmision:

MainActivity.super.requestAppPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestcodeWriteStorage);

你也可以检查很多权限,你应该在String Array中定义;

requestcodeWriteStorage是一个你应该定义它的int;

使用我读过的2方法管理您的回调。

例如:

@Override
public void onPermissionsGranted(int requestCode) {
    if (requestCode == requestcodeWriteStorage){
        Toast.makeText(this,"Done",Toast.LENGTH_LONG).show();

    }

答案 4 :(得分:0)

在5.0及更高版本中,您还必须授予您的应用在设置中读取短信的权限。

答案 5 :(得分:0)

确保你已经为你的应用程序使用了Android Android 6.0及更高版本的SDK,我遇到了同样的问题,我发现我使用了android 4.1 kitkat sdk,一旦我将min sdk级别更改为21,问题解决了