Android 查询一条短信

整体流程

我们首先来看一下整个查询一条短信的流程:

journey
    title 查询一条短信流程
    section 开发者
        开发者->小白: 授课
    section 小白
        小白->手机: 打开短信应用
        小白->手机: 找到要查询的短信
        小白->手机: 记住短信内容

每一步的操作及代码

步骤1:打开短信应用

// 打开短信应用
Intent smsIntent = new Intent(Intent.ACTION_VIEW);
smsIntent.setType("vnd.android-dir/mms-sms");
startActivity(smsIntent);

步骤2:找到要查询的短信

// 查询短信的投影
String[] projection = new String[]{"_id", "address", "body", "date"};
// 查询条件
String selection = "address = ? AND date = ?";
// 查询条件的参数
String[] selectionArgs = new String[]{"1234567890", "1612345678901"};
// 查询短信
Cursor cursor = getContentResolver().query(Uri.parse("content://sms/"), projection, selection, selectionArgs, "date DESC");

步骤3:记住短信内容

// 移动光标到第一行
if (cursor.moveToFirst()) {
    // 获取短信内容
    String address = cursor.getString(cursor.getColumnIndex("address"));
    String body = cursor.getString(cursor.getColumnIndex("body"));
    // 记住短信内容
    Log.d("SMS", "Address: " + address + ", Body: " + body);
}
cursor.close();

完整流程

participant 开发者
participant 小白
participant 手机

开发者->小白: 授课
小白->手机: 打开短信应用
手机->小白: 显示短信列表
小白->手机: 找到要查询的短信
手机->小白: 显示短信内容
小白->手机: 记住短信内容

通过以上步骤,你可以成功查询一条短信。希望这篇文章对你有所帮助,加油!如果有任何问题都可以随时向我提问。