-1

这是我读取 OTP 编号的类,它在所有设备中都可以正常工作,但在棉花糖中它不读取 OTP 编号。我知道要解决此问题,它需要运行时权限,但我不知道如何授予运行时权限以读取服务器发送的 OTP 编号。

 public class IncominMsg extends BroadcastReceiver {

    final SmsManager smsManager = SmsManager.getDefault();

    public static String GENERAL_OTP_TEMPLATE = "(.*) is your OTP for Reset Password for your app. Treat this as a confidential";
    public static final String KEY_PREFERNCE = "prefernce";
    public static final String KEY_OTP = "otp";
    String otp;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    private final int REQUEST_CODE_ASK_FOR_PERMISSIONS = 1234;

    @Override
    public void onReceive(Context context, Intent intent) {

        final Bundle bundle = intent.getExtras();

        int permissionCheck = ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_SMS);
        sharedPreferences = context.getSharedPreferences(KEY_PREFERNCE, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();

        Activity activity = (Activity) context;

        try {
            if (bundle != null) {
                final Object[] pdusObj = (Object[]) bundle.get("pdus");
                SmsMessage[] smsMessages = new SmsMessage[pdusObj.length];

                for (int i = 0; i < pdusObj.length; i++) {

                    smsMessages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                    String message = smsMessages[i].getDisplayMessageBody();

                }

                Pattern generalOtpPattern = Pattern.compile(GENERAL_OTP_TEMPLATE);
                Matcher generalOtpMatcher = generalOtpPattern.matcher(smsMessages[0].getMessageBody().toString());

                if (generalOtpMatcher.find()) {
                    permissionCheck = ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_SMS);
                    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {

                        ActivityCompat.requestPermissions(activity, new String[]{android.Manifest.permission.READ_SMS}, REQUEST_CODE_ASK_FOR_PERMISSIONS);
                        return;

                    }

                    otp = generalOtpMatcher.group(1);//this is only your OTP code

                    editor.clear();
                    editor.putString(KEY_OTP, otp);
                    editor.commit();
                }
            }
        } catch (Exception e) {

        }
    }
}
4

1 回答 1

0

READ_SMS您可以像这样在运行时请求许可 -

final private int REQUEST_CODE_ASK_FOR_PERMISSIONS = 752136975889;

private void askForReadSMSPermission() {
    int hasReadSMSPermission = checkSelfPermission(Manifest.permission.READ_SMS);
    if (hasReadSMSPermission != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[] {Manifest.permission.READ_SMS},
                REQUEST_CODE_ASK_FOR_PERMISSIONS);
        return;
    }

    //Your code to read the OTP

}

PS不要忘记<uses-permission-sdk-23/>在AndroidManifest.xml中添加

于 2016-09-13T07:11:19.653 回答