Listening for SMS and automatically replying to it in Android

你。 提交于 2019-12-24 09:57:39

问题


How to reply to an incoming message automatically in android?

Here's my onReceive() method from my IncomingSMS class which extends BroadcastRecevier, problem with it is that it sends many messages, I want it to send only one SMS reply.

public class IncomingSMS extends BroadcastReceiver{
private String senderNumber;

@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    SmsMessage[] msgs = null;

    String message = "";            

    if(bundle != null){
        Object[] pdus = (Object[]) bundle.get("pdus");
        msgs = new SmsMessage[pdus.length];



        for(int i = 0; i < msgs.length; i++){
            msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
            message = msgs[i].getMessageBody();
            senderNumber = msgs[i].getOriginatingAddress();
        }
        senderNumber = msgs[0].getOriginatingAddress();

        Toast.makeText(context, message, Toast.LENGTH_LONG).show();
        sendMessage(senderNumber, "Thank you for sending me a message");
    }
}

private void sendMessage(String number, String message) {
    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(number, null, message, null, null);
}

回答1:


What you are facing is the normal behavior. Since you are listening for all incoming SMS, it is bound to send out a SMS again when it receives the thank you message. What you can do is, send a value or a boolean which is unique in the SMS and put a check for it. If the value exists you simply don't send the message again.




回答2:


Onrecieve run after receiving of any part of sms and send a sms after of receiving of any part.i think you should set a time for receiving of part of sms and after pass that time you send reply of sms



来源:https://stackoverflow.com/questions/21995244/listening-for-sms-and-automatically-replying-to-it-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!