读取收件箱中指定号码的最新短信

本文介绍如何使用Android的ManagedQuery()方法从短信收件箱中提取特定信息。通过实例演示了如何设置URI、Projection、Selection等参数,并展示了如何解析短信内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、首先简单介绍一下:ManagedQuery()

参数:

1.URI:content provider需要返回的资源索引。例如:收信箱:

content://sms/inbox

2.Projection: 用于标识有哪些columns需要包含在返回数据中。例如:id号,地址,消息体,读取状态。。。

new String[] {"_id", "address", "body", "read"}

3.Selection:作为查询符合条件的过滤参数。

"address=? and read=?"

4.SelectionArgs:同上

new String[] { "15061978220", "1" }

5.SortOrder:对于返回信息进行排列。

"date desc"


面临的两个问题:1.如何提取消息体body。

                       2.如何提取body中的有效信息。

String smsbody = cursor.getString(cursor.getColumnIndex("body"));
String code = smsbody.substring(smsbody.indexOf(",") +1, smsbody.indexOf("."));
//用subString提取子字符串,以“,”开始,“。”结束。用indexOf("")取得字符串的位置。


现在贴上源程序

package my.learn.ReadSMS;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class ReadSMSActivity extends Activity {
// final String SMS_URL_INBOX="content://sms/inbox";
private Button mybtn;
private TextView mtTxt;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mybtn = (Button) findViewById(R.id.clickButton);
mtTxt = (TextView) findViewById(R.id.showTxt);
}

public void doReadSMS(View view) {
Cursor cursor = null;// 光标
cursor = managedQuery(Uri.parse("content://sms/inbox"), new String[] {
"_id", "address", "body", "read" }, "address=? and read=?",
new String[] { "15061978220", "1" }, "date desc");
if (cursor != null) {// 如果短信为已读模式
cursor.moveToFirst();
if (cursor.moveToFirst()) {

String smsbody = cursor
.getString(cursor.getColumnIndex("body"));
String code = smsbody.substring(smsbody.indexOf(",") + 1,
smsbody.indexOf("."));
mtTxt.setText(code.toString());
}

}

}
}

在没有真机的情况下,我们可以通过模拟器来实现。

首先在DDMS的模式下,“Emulator Control” ,"InComing number",选择"SMS",填入需要的“Message”,点击“send”按钮,这样模拟器就可以接收到短信了。

程序运行结果:



 

 

转载于:https://www.cnblogs.com/sarah-susan/archive/2012/02/05/2339098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值