android接收跟发送短信的xml配置

android接收和发送短信的xml配置

<!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL/> <w:BalanceSingleByteDoubleByteWidth/> <w:DoNotLeaveBackslashAlone/> <w:ULTrailSpace/> <w:DoNotExpandShiftReturn/> <w:AdjustLineHeightInTable/> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:UseFELayout/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!-- [if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><!-- [if gte mso 10]> <style> /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} </style> <![endif]-->

andoird 2010-03-23 15:59:00 阅读 115 评论 1 字号: 大中

1.android 发送短信
                android API
中提供了 smsManager 类处理短信。其中的 sendTextMessage(num, null, content, pend, null) 函数就是发送
       
短信的方法。第一个参数为目标者手机号、第二个参数为短信中心地址 null 为默认地址、
       
第三个参数短信的文本内容、第四个参数是一个 intent 会把发送结果带回。第五个参数不知,一般为 null
              
               
一个应用程序要具备发送短信功能,需要在 androidManifest.xml 中加入 android.permission.SEND_SMS 权限。
              
               
在模拟器中发送中文会接收方出现乱码的问题,但是在真机中,就不会出现乱码的情况了。所以
       
开发者只需要正常开发短信功能,不需要编码转换。

接收短信也是比较方便的,主要是继承 BroadcaseReceiver , 覆盖 onReceive 函数:

1:
相关类:
android.content.BroadcastReceiver
android.telephony.gsm.SmsMessage;

2:example code.

public class MessageDemo extends BroadcastReceiver {
    private static final String strACT = "android.provider.Telephony.SMS_RECEIVED";

public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(strACT)) {
StringBuilder sb = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] msg = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (SmsMessage currMsg : msg) {
sb.append("From:");
sb.append(currMsg.getDisplayOriginatingAddress());
sb.append("\nMessage:");
sb.append(currMsg.getDisplayMessageBody());
}
}
}

}
}
3:
相关的配置

修改 AndroidManifest.xml ,在 Activity 下添加 receiver 节点:
<receiver android:name="MessageDemo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
随后在 application 下添加节点:
<uses-permission android:name="android.permission.SEND_SMS"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

4:
使用 BroadReceiver 的弊端
查看 BroadReceiver sdk reference , 可以了解到所有的 BroadReceiver 对短信的接收是无顺序的状态 ,即使是使用了 Ordered broadcasts 对于同等优先级别的 BroadReceiver , 也会产生无顺序的行为。
所以下面介绍另一种接收短信的行为,包括其中可以进行短信的删除。

5
:从数据库端监听 sms 的收发
//
如下 主要用于内部数据库改变,向外面的界面 (Activity) 做反应
class SMSHandler extends Handler
{
    public void handleMessage(Message msg)
    {
        //Handle message
    }
}

//
对收到短消息后,做出的处理 , 这里直接删除,并没有反应到界面,所以上面的 handleMessage 是空的。
class SMSObserver extends ContentObserver
{
    private Handler m_handle = null;

    public SMSObserver(Handler handle)
    {
        super(handle);
        m_handle = handle;
    }

    public void onChange(boolean bSelfChange)
    {
        super.onChange(bSelfChange);

        //Send message to Activity
        Message msg = new Message();
        msg.obj = "xxxxxxxxxx";
        m_handle.sendMessage(msg);

String strUriInbox = "content://sms/inbox";
Uri uriSms = Uri.parse(strUriInbox);  //If you want to access all SMS, just replace the uri string to "content://sms/"
Cursor c = mContext.getContentResolver().query(uriSms, null, null, null, null);
// delete all sms here when every new sms occures.
while (c.moveToNext())
{  
       //Read the contents of the SMS;
       for(int i; i < c.getColumnCount(); i++)
        {
            String strColumnName = c.getColumnName(i);
            String strColumnValue = c.getString(i);
        }


       //Delete the SMS
        String pid = c.getString(1);  //Get thread id;
       String uri = "content://sms/conversations/" + pid;
       mContext.getContentResolver().delete(Uri.parse(uri), null, null);      
  
}

        


    }
}

//
把基本类功能性地应用起来
ContentResolver contentResolver = getContentResolver();// Context
环境下 getContentResolver()
Handler handler = new SMSHandler();
ContentObserver m_SMSObserver = new SMSObserver(handler);
contentResolver.registerContentObserver(Uri.parse("content://sms/inbox"),true, m_SMSObserver);
//Register to observe SMS in outbox,we can observe SMS in other location by changing Uri string, such as inbox, sent, draft, outbox, etc.)

// some Available Uri string  for sms.
/*
  String strUriInbox = "content://sms/inbox";//SMS_INBOX:1
  String strUriFailed = "content://sms/failed";//SMS_FAILED:2
  String strUriQueued = "content://sms/queued";//SMS_QUEUED:3
  String strUriSent = "content://sms/sent";//SMS_SENT:4
  String strUriDraft = "content://sms/draft";//SMS_DRAFT:5
  String strUriOutbox = "content://sms/outbox";//SMS_OUTBOX:6
  String strUriUndelivered = "content://sms/undelivered";//SMS_UNDELIVERED
  String strUriAll = "content://sms/all";//SMS_ALL
  String strUriConversations = "content://sms/conversations";//you can delete one conversation by thread_id
  String strUriAll = "content://sms"//you can delete one message by _id
*/

REMEBER: must request following permission
1) Read SMS
    <uses-permssion android:name="android.permission.READ_SMS" />
2) Delete/Modify/Send SMS
    <uses-permssion android:name="android.permission.WRITE_SMS" />
in AndroidManifest.xml