---
title: "SMS短信服务处理和获取联系人"
author: "wghjay"
date: "2009-07-07T15:22:13Z"
tags: []
slug: "sms"
draft: false
lastmod: "2009-07-07T15:22:13Z"
id: 421270
url: "https://wghjay.iteye.com/blog/421270"
---

许多新的应用程序会考虑使用SMS作为数据分发平台。现实一点的场景：电影点播系统要求用户发送一定格式的短信来进行自动点播。现在越来越多的应用采用SMS作为与用户进行数据交换的方式。现在让我们来看一下我们如何在Android平台上来构造这种形式的应用。

 

Android API支持开发可以发送和接收SMS消息的应用程序。目前我们开发过程中使用的Android模拟器还不支持发送SMS，但它可以接收SMS。现在我们来 探索一下Android对SMS的支持，我们将会构建一个小小的应用程序来监听移动设备（或模拟器）上接收到的SMS消息，并将它显示出来。

 

我们来定义一个Intent接收器来处理SMS接收事件：

**package com.wissen.sms.receiver;**

**public class SMSReceiver extends BroadcastReceiver {**  
    **@Override**  
    **public void onReceive(Context context, Intent intent) {**  
       **// TODO**  
    **}**  
**}**

我们需要对这个Intent接收器进行配置以使它能获取SMS接收事件，‘ android.provider.Telephony.SMS\_RECEIVED’这个事件状态表示了SMS已被接收。我们可以在AndroidManifest.xml中进行如下配置：

**&lt;receiver android:name=”.receiver.SMSReceiver” android:enabled=”true”&gt;**  
**&lt;intent-filter&gt;**  
**&lt;action android:name=”android.provider.Telephony.SMS\_RECEIVED” /&gt;**  
**&lt;/intent-filter&gt;**  
**&lt;/receiver&gt;**

为了能让我们的应用能接收SMS,我们得先进行权限的指定，可以在AndroidManifest.xml中如下配置：

&lt;uses-permission android:name=”android.permission.RECEIVE\_SMS”&gt;&lt;/uses-permission&gt;

现在，我们的Intent接收器就可以在Android设备接收到SMS的时候被调用了，余下的事情就是去获取和显示接收到的SMS消息文本了：

*public void onReceive(Context context, Intent intent) {*  
        *Bundle bundle = intent.getExtras();*  
        *Object messages\[] = (Object\[]) bundle.get(”pdus”);*  
        *SmsMessage smsMessage\[] = new SmsMessage\[messages.length];*  
        *for (int n = 0; n &lt; messages.length; n++) {*  
                *smsMessage\[n] = SmsMessage.createFromPdu((byte\[]) messages\[n]);*  
       *}*  
      *// show first message*  
      *Toast toast = Toast.makeText(context, “Received SMS: ” + smsMessage\[0].getMessageBody(),                Toast.LENGTH\_LONG);*  
      *toast.show();*  
*}*

Android设备接收到的SMS是以pdu形式的(protocol description unit)。android.telephony.gsm.SmsMessage这个类可以储存SMS的相关信息，我们也可以从接收到的pdu中创建新的SmsMessage实例，Toast界面组件可以以系统通知的形式来显示接收到的SMS消息文本。

 

运行程序：

现在让我们来在模拟器中运行这个应用程序，以及发送SMS消息到这个模拟器上。我们可以在eclipse的Android插件所提供的DDMS视图(Dalvik Debug Monitor Service)中发送SMS消息到模拟器上（在’Emulator Control’面板中；另外需要指定电话电话号码，不过可以是任意的）

 

***发出广播Intent的方法***

**public static final String MUSIC\_ACTION="com.mythlink.MUSIC";**

**Intent intent=new Intent();**  
**intent.setAction(MUSIC\_ACTION);**  
**intent.putExtra("music\_path", songPath);**  
**this.sendBroadcast(intent);**

**需要再写一个广播接收器**

 

*public class MusicReceiver extends BroadcastReceiver {*

 *@Override*  
 *public void onReceive(Context context, Intent intent) {*  
  *Bundle bundle=intent.getExtras();*  
  *String music\_path=bundle.getString("music\_path");*  
  *Toast toast=Toast.makeText(context, "Playing music:"+music\_path, Toast.LENGTH\_LONG);*  
  *toast.show();*  
 *}*

*}*

 

***获取联系人信息***

 

*public class ContactsList extends ListActivity {*

 *private ListAdapter mAdapter;*

 *@Override*  
 *protected void onCreate(Bundle savedInstanceState) {*  
  *super.onCreate(savedInstanceState);*  
  *Cursor c=this.getContentResolver().query(Contacts.People.CONTENT\_URI, null, null, null, null);*  
  *this.startManagingCursor(c);*  
    
  *String\[] columns=new String\[]{Contacts.People.NAME};*  
  *int\[] names=new int\[]{R.id.song};////////////////*  
  *mAdapter = new SimpleCursorAdapter(this, R.layout.song\_item, c, columns, names);*  
  *this.setListAdapter(mAdapter);*  
 *}*

 *@Override*  
 *protected void onListItemClick(ListView l, View v, int position, long id) {*  
  *super.onListItemClick(l, v, position, id);*  
  *Intent i=new Intent(Intent.ACTION\_CALL);*  
  *Cursor c = (Cursor) mAdapter.getItem(position);*  
     *long phoneID = c.getLong(c.getColumnIndex(Contacts.People.PRIMARY\_PHONE\_ID));*  
     *i.setData(ContentUris.withAppendedId(Contacts.Phones.CONTENT\_URI, phoneID));*  
     *this.startActivity(i);*

 *}*  
   
   
*}*

**在Androidmanifest.xml中加入**

*&lt;uses-permission android:name="android.permission.READ\_CONTACTS"/&gt;*

  *&lt;activity android:name=".ContactsList"*  
                  *android:label="@string/app\_name"&gt;*  
            *&lt;intent-filter&gt;*  
                *&lt;action android:name="android.intent.action.MAIN" /&gt;*  
                *&lt;category android:name="android.intent.category.LAUNCHER" /&gt;*  
            *&lt;/intent-filter&gt;*  
        *&lt;/activity&gt;*

 

来源：[http://zarknight.iteye.com/blog/351614](http://zarknight.iteye.com/blog/351614)