一、首先簡單介紹一下: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:對於返回資訊進行排列。
面臨的兩個問題: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”按鈕,這樣模擬器就可以接收到簡訊了。
程式運行結果: