獲取手機的短信內容和聯繫人信息

獲取短信內容:

編寫一個廣播接收器(ShortMessageReceiver),其中onReceive方法的代碼如下:

public void onReceiver(Context context,Intent intent){
 Bundle bundle = intent.getExtras();
  if (bundle != null){
   //獲得收到的短信數據
   Object[] objArray  (Object[]) bundle.get("pdus");
   //定義封裝短信內容的SmsMessage對象數組
   SmsMessage[] messages=new SmsMessage[objArray.length];
   //循環處理收到的所有短信
        for (int i=0;i<objArray.length;i++){
           //將每條短信數據轉換成SmsMessage對象
           messages[i] =SmsMessage.createFormPdu((byte[]) objArray[i]);
           //獲得發送短信的電話號碼和短信內容
           String s ="手機號:"+messages[i].getDisplayMessageBody();
           //顯示發送短信的電話號碼和短信內容
           Toast.makeText(Context,s,Toast.LENGTH_LONG).show();
         }
   }
}

然後在AndroidMainfest.xml文件中定義ShortMessageReceiver時添加短信廣播Action即可,代碼如下:

</pre><pre name="code" class="html"><receiver android:name=".ShortMessageReceiver">
    android:enabled="true"
    <intent-filter>
       <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    </intent-filter>
 </receiver>




讀取聯繫人信息:
使用Content Provider可以讀取聯繫人信息。如下的代碼讀取了所有聯繫人信息,並將聯繫人名稱顯示在ListView組件中:

ListView listView = (ListView) findViewById(R.id.listview);
 //查詢系統中所有聯繫人
 Cursor cursor = getContentResolver().query(
                     ContactsContacts.CONTENT_URI,null,null,null,null);
  //根據cursor創建SimpleCursorAdapter對象
  SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_1,cursor,new String[]
                        { CountactsContract.Contacts.DISPLAY_NAME},new int[]
                        {android.R.id.text1}  );
   //在ListView控件中顯示聯繫人列表
  listView.setAdapter(simpleCursorAdapter);


讀取聯繫人信息時,要在AndroidMainfest.xml文件中設置如下權限:
   <uses-permission android:name="android.permission.READ_CONTACTS"/>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章