Search code examples
androidsmsbroadcastreceiver

Listening to incoming texts, in the background


I'm trying to make my application listen to incoming text messages, in a persistent manner. What would be the best approach for this?

Currently, I've got a working BroadcastReceiver and I'm playing around with implementing a local service for my app. Is somehow implementing the BroadcastReceiver into the service the correct way of doing this? Will the service work in a low memory condition?


Solution

  • Yes broadcast receiver is best way for listening to incoming texts.if an incoming sms recvied use IntentService for your work what u want to do on sms recived.u can register a reciver for incoming sms as:

    manifest file

    <receiver class="SMSApp">  
       <intent-filter>  
          <action android:value="android.provider.Telephony.SMS_RECEIVED" />  
         </intent-filter>  
    </receiver>  
    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    

    Java File

        public class SMSApp extends BroadcastReceiver{
        private static final String LOG_TAG = "SMSApp"; 
        /* package */
        static final String ACTION = "android.provider.Telephony.SMS_RECEIVED"; 
        public void onReceive(Context context, Intent intent){ 
            if (intent.getAction().equals(ACTION)){ 
              Bundle bundle = intent.getExtras();
              if (bundle != null){
                   Object[] pdus = (Object[]) bundle.get("pdus");
                   SmsMessage[] messages = new SmsMessage[pdus.length];
                   for (int i = 0; i < pdus.length; i++){
                     messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                   }
                   for (SmsMessage message : messages){
                        String strFrom = message.getDisplayOriginatingAddress();
                        String strMsg = message.getDisplayMessageBody();
                   }
                }    
            } 
        } 
    }    
    

    and second way you can register a ContentObserver for content://sms/inbox for listening incoming sms in inbox