android手機開發之讀取收件匣中指定號碼簡訊

來源:互聯網
上載者:User

一、首先簡單介紹一下: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”按鈕,這樣模擬器就可以接收到簡訊了。

程式運行結果:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.