Android – Listen For Incoming SMS Messages

后端 未结 9 1458
情话喂你
情话喂你 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:33

    In case you want to handle intent on opened activity, you can use PendintIntent (Complete steps below):

    public class SMSReciver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent 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();
                        try {
                            if (senderNum.contains("MOB_NUMBER")) {
                                Toast.makeText(context,"",Toast.LENGTH_SHORT).show();
    
                                Intent intentCall = new Intent(context, MainActivity.class);
                                intentCall.putExtra("message", currentMessage.getMessageBody());
    
                                PendingIntent pendingIntent= PendingIntent.getActivity(context, 0, intentCall, PendingIntent.FLAG_UPDATE_CURRENT);
                                pendingIntent.send();
                            }
                        } catch (Exception e) {
                        }
                    }
                }
            } catch (Exception e) {
            }
        }
    } 
    

    manifest:

    
    
                
                    
                
            
    

    onNewIntent:

     @Override
             protected void onNewIntent(Intent intent) {
                    super.onNewIntent(intent);
                    Toast.makeText(this, "onNewIntent", Toast.LENGTH_SHORT).show();
    
                    onSMSReceived(intent.getStringExtra("message"));
    
                }
    

    permissions:

    
    
    
    

提交回复
热议问题