在Android 5.0中,可以通过ContentResolver和Uri获取短信。首先需要添加读取短信的权限,然后使用ContentResolver查询系统短信表。
在Android中,获取短信需要使用短信相关的API,以下是详细的步骤和小标题:
1、添加权限
在AndroidManifest.xml文件中添加以下权限:
<usespermission android:name="android.permission.READ_SMS" /> <usespermission android:name="android.permission.RECEIVE_SMS" />
2、创建广播接收器
创建一个名为SmsReceiver的广播接收器,继承自BroadcastReceiver,并重写onReceive方法。
public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); for (int i = 0; i < pdus.length; i++) { SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdus[i]); String sender = smsMessage.getDisplayOriginatingAddress(); String messageBody = smsMessage.getDisplayMessageBody(); // 在这里处理短信内容,例如显示在UI上或者存储到数据库等 } } } }
3、注册广播接收器
在AndroidManifest.xml文件中注册SmsReceiver:
<receiver android:name=".SmsReceiver"> <intentfilter> <action android:name="android.provider.Telephony.SMS_RECEIVED" /> </intentfilter> </receiver>
4、处理权限请求
如果应用的目标版本是Android 6.0(API级别23)或更高,需要在运行时检查和请求READ_SMS和RECEIVE_SMS权限,可以使用ActivityCompat类的requestPermissions方法来请求权限,以下是示例代码:
private static final int SMS_PERMISSION_REQUEST_CODE = 100; private String[] permissions = new String[]{Manifest.permission.READ_SMS, Manifest.permission.RECEIVE_SMS}; private void checkAndRequestPermissions() { if (!hasPermissions()) { ActivityCompat.requestPermissions(this, permissions, SMS_PERMISSION_REQUEST_CODE); } else { registerSmsReceiver(); } } private boolean hasPermissions() { for (String permission : permissions) { if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) { return false; } } return true; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == SMS_PERMISSION_REQUEST_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { registerSmsReceiver(); } else { Toast.makeText(this, "需要读取短信的权限", Toast.LENGTH_SHORT).show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
5、注册广播接收器(已处理权限)
在检查并请求权限后,如果用户授予了权限,可以注册SmsReceiver,以下是示例代码:
private void registerSmsReceiver() { IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED"); registerReceiver(new SmsReceiver(), filter); }