Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

android - How to send and receive data SMS messages

I've found a few tutorials on how to send/receive text SMS messages, but none on how to send/receive data SMS messages. I have a very small amount of data I would like the users of my app to be able to share.

I am able to send, but my BroadcastReceiver doesn't ever get called. It seems this is a known issue (http://code.google.com/p/android/issues/detail?id=1576) but has anyone figured out how to do this yet?

I tried sending/receiving a text SMS and that works fine, the thing is, I need to specify a port so only my app can listen for the SMS.


It seems this question has been asked here before and was never answered: how to receive text sms to specific port..

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I know this is 1 year old at time of my response, but I thought it could still help someone.
Receiving:

Bundle bundle = intent.getExtras(); 

            String recMsgString = "";            
            String fromAddress = "";
            SmsMessage recMsg = null;
            byte[] data = null;
            if (bundle != null)
            {
                //---retrieve the SMS message received---
               Object[] pdus = (Object[]) bundle.get("pdus");
                for (int i=0; i<pdus.length; i++){
                    recMsg = SmsMessage.createFromPdu((byte[])pdus[i]);

                    try {
                        data = recMsg.getUserData();
                    } catch (Exception e){

                    }
                    if (data!=null){
                        for(int index=0; index<data.length; ++index)
                        {
                               recMsgString += Character.toString((char)data[index]);
                        } 
                    }

                    fromAddress = recMsg.getOriginatingAddress();
                }

Setting up Receiver in Manifest:

<receiver android:name=".SMSReceiver"> 
        <intent-filter>
        <action android:name="android.intent.action.DATA_SMS_RECEIVED" /> 
            <data android:scheme="sms" /> 
            <data android:port="8901" /> 
        </intent-filter> 
</receiver> 

Sending:

String messageText = "message!"; 
short SMS_PORT = 8901; //you can use a different port if you'd like. I believe it just has to be an int value.
SmsManager smsManager = SmsManager.getDefault(); 
smsManager.sendDataMessage("8675309", null, SMS_PORT, messageText.getBytes(), null, null); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...