android手机开发之读取收件箱中指定号码短信

作者:简简单单 2012-02-07

一、首先简单介绍一下: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”按钮,这样模拟器就可以接收到短信了。

程序运行结果:

相关文章

精彩推荐