要获取Android 7.0上的短信,您需要先请求READ_SMS和RECEIVE_SMS权限。然后,您可以使用ContentResolver访问短信的Uri,并使用Cursor读取短信。以下是一个示例代码:
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED
&& ContextCompat.checkSelfPermission(this, Manifest.permission.RECEIVE_SMS) == PackageManager.PERMISSION_GRANTED) {
Uri uri = Uri.parse("content://sms/inbox");
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
// Do something with the address and body of the SMS
}
if (cursor != null) {
cursor.close();
}
} else {
// Request runtime permissions
}
请注意,您需要在应用中处理运行时权限,以避免在用户未授予权限的情况下访问短信。
获取短信需要获取短信读取权限,Android 6.0 及以上版本需要动态申请权限。
首先,在 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
然后,在代码中添加动态权限申请:
![佛山阿里云代理商:android 7.0 获取短信](https://www.jintuiyun.com/wp-content/themes/justnews/themer/assets/images/lazy.png)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// 判断 Android 版本是否大于等于 6.0
if (checkSelfPermission(Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED) {
// 如果未授权,则向用户申请授权
requestPermissions(new String[] {Manifest.permission.READ_SMS}, 1);
}
}
// 授权结果回调方法
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 用户授权
// 进行获取短信的操作
} else {
// 用户拒绝授权
Toast.makeText(this, "请授权以获取短信", Toast.LENGTH_SHORT).show();
}
}
}
获取短信的代码如下:
Uri uri = Uri.parse("content://sms/inbox");
// 查询条件,只查询发送号码包含139的短信
String selection = "address like '%139%'";
Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
if (cursor != null && cursor.getCount() > 0) {
// 遍历短信
while (cursor.moveToNext()) {
String address = cursor.getString(cursor.getColumnIndex("address"));
String body = cursor.getString(cursor.getColumnIndex("body"));
// 处理短信
}
cursor.close();
}
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/159255.html