Android短信数据(6.0)操作简介

添加权限

 
 

Android6.0获取手机短信动态权限

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
  if (ContextCompat.checkSelfPermission(getBaseActivity(), Manifest.permission.READ_SMS)
                != PackageManager.PERMISSION_GRANTED) 
    requestPermissions(new String[]{Manifest.permission.READ_SMS}, 1002);
}

获取权限回调

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
  super.onRequestPermissionsResult(requestCode, permissions, grantResults);
  switch (requestCode) {
    case 1001:
      if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      }
      break;
    }
}

读取短信工具

public class SMSUtils {
    private final static String sms = "content://sms/";//所有短信
    private final static String inbox = "content://sms/inbox";//收件箱
    private final static String sent = "content://sms/sent";//已发送
    private final static String draft = "content://sms/draft";//草稿
    private final static String outbox = "content://sms/outbox";//发件箱
    private final static String failed = "content://sms/failed";//发送失败
    private final static String queued = "content://sms/queued";//待发送列表

    public static List smsQuery(Context context) {
        List smsInfoList = new ArrayList<>();
        Uri uri = Uri.parse(sms);
        ContentResolver resolver = context.getContentResolver();
        String[] projection = new String[]{"address", "body", "date", "type"};
        Cursor cursor = resolver.query(uri, projection, null, null, "date desc");
        if (cursor != null)
            while (cursor.moveToNext()) {
                SMSInfo smsInfo = new SMSInfo();
                smsInfo.setAddress(cursor.getString(0));
                smsInfo.setBody(cursor.getString(1));
                smsInfo.setDate(cursor.getString(2));
                smsInfo.setType(cursor.getInt(3));
                smsInfoList.add(smsInfo);
            }
        return smsInfoList;
    }
}

拦截广播监听短信

public class SmsReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        SmsMessage msg = null;
        if (null != bundle) {
            Object[] smsObj = (Object[]) bundle.get("pdus");
            for (Object object : smsObj) {
                msg = SmsMessage.createFromPdu((byte[]) object);
                Date date = new Date(msg.getTimestampMillis());// 时间
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String receiveTime = format.format(date);
                msg.getOriginatingAddress();
                msg.getDisplayMessageBody();
                msg.getTimestampMillis();
            }
        }
    }
}

注册广播


    
      
      
    

应用观察者模式监听短信数据库

public class SMSCodeObserver extends ContentObserver {
    private Handler handler;

    public SMSCodeObserver(Handler handler) {
        super(handler);
        this.handler = handler;
    }

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);
        handler.obtainMessage(1, "SMS Received").sendToTarget();
    }
}

接收处理发送的消息

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case 1:
                setSmsCode();
                break;
        }
    }
};

获取当前短信的验证码

    private void setSmsCode() {
        Cursor cursor = null;
        cursor = getBaseActivity().getContentResolver().query(Uri.parse("content://sms/inbox"),
                new String[]{"_id", "address", "read", "body", "date"},
                null, null, "date desc");
        if (cursor != null) {
            String body = "";
            while (cursor.moveToNext()) {
                body = cursor.getString(cursor.getColumnIndex("body"));// 在这里获取短信信息
                long smsDate = Long.parseLong(cursor.getString(cursor.getColumnIndex("date")));
                long nowDate = System.currentTimeMillis();
                // 如果当前时间和短信时间间隔超过60秒,认为这条短信无效
                if (nowDate - smsDate > 60 * 1000) {
                    break;
                }
                Pattern pattern = Pattern.compile("\\d{6}");
                Matcher matcher = pattern.matcher(body);
                if (matcher.find()) {
                    String smsCodeStr = matcher.group(0);
                    break;
                }
            }
        }
    }

你可能感兴趣的:(Android短信数据(6.0)操作简介)