Search code examples
androidbroadcastreceivercontentobserver

Detecting incoming and outgoing sms?


Is it Good paractice to Detect Incoming and Outgoing Sms through ContentObserver or use BroadCast Receiver for Incoming SMS and ContentObserver for Outgoing Sms??


Solution

  • I had an application about SMS and Call blocker but i never upload it to play store because of after Kitkat ,you cant block sms messages. If you wanna do that just dont. I am sharing the sms part only, you can modify it as you want.

    <!-- Android Permissions in manifest -->
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    
    <!-- Define receiver inside the application tag -->
    <receiver android:name="catchPackage.SmsController" android:process=":hascode_process" android:label="@string/sms_receiver"
            android:permission="android.permission.BROADCAST_SMS">
            <intent-filter android:priority="999">
                <action android:name="android.provider.Telephony.SMS_DELIVER"/>
                <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
            </intent-filter>
        </receiver>
    <!-- Broadcast receiver java code -->
    
     public void onReceive(Context context, Intent intent) {
        this.context = context;
              try{
                  Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
                    SmsMessage[] msgs = null;
                    String msg_from = null;
                    String msg_body = null;
                    if (bundle != null){
                        try{
    
                            boolean delete= false;
                            Object[] pdus = (Object[]) bundle.get("pdus");
                            msgs = new SmsMessage[pdus.length];
                            for(int k=0; k<msgs.length; k++){
                                msgs[k] = SmsMessage.createFromPdu((byte[])pdus[k]);
                                msg_from = msgs[k].getOriginatingAddress();
                                System.out.println(msg_from);
                                String msgBody = msgs[k].getMessageBody();
                                msg_body = msgBody;
    
    
                            }
    
                        }catch(Exception e){
                            System.out.println(e.getMessage());
                        }
                    }
                } catch (Exception e) {
                    Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
                    e.printStackTrace();
                }
        }
    
    }