Android – Listen For Incoming SMS Messages

后端 未结 9 1471
情话喂你
情话喂你 2020-11-22 07:06

I am trying to create an application for monitoring incoming SMS messages, and launch a program via incoming SMS, also it should read the content from the SMS.

Workf

9条回答
  •  死守一世寂寞
    2020-11-22 07:36

    This is what i used!

    public class SMSListener extends BroadcastReceiver {
    
        // Get the object of SmsManager
        final SmsManager sms = SmsManager.getDefault();
    String mobile,body;
    
        public void onReceive(Context context, Intent intent) {
    
            // Retrieves a map of extended data from the intent.
            final Bundle bundle = intent.getExtras();
    
            try {
    
                if (bundle != null) {
    
                    final Object[] pdusObj = (Object[]) bundle.get("pdus");
    
                    for (int i = 0; i < pdusObj.length; i++) {
    
                        SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                        String phoneNumber = currentMessage.getDisplayOriginatingAddress();
    
                        String senderNum = phoneNumber;
                        String message = currentMessage.getDisplayMessageBody();
                         mobile=senderNum.replaceAll("\\s","");
                         body=message.replaceAll("\\s","+");
    
    
                        Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + body);
    
    
                        // Show Alert
                        int duration = Toast.LENGTH_LONG;
                        Toast toast = Toast.makeText(context,
                                "senderNum: "+ mobile+ ", message: " + message, duration);
                        toast.show();
    
                    } // end for loop
                } // bundle is null
    
            } catch (Exception e) {
                Log.e("SmsReceiver", "Exception smsReceiver" +e);
    
            }
        }
    }
    

提交回复
热议问题