rohan c
rohan c

Reputation: 31

Receive SMS and show notification

I'm trying to build a code that shows notification on SMS receive. My problem is that how do I implement broadcast receiver to my main activity because in my main activity I also have other functions working. If I try to create another class that extends broadcast receiver then how do I call that from the main class? Does it automatically start the function as soon as the message is received or does it need to be provoked from the main activity?

Upvotes: 0

Views: 6588

Answers (3)

anotherGatsby
anotherGatsby

Reputation: 1598

did you see this question ? anyway try this :

public class SmsListener extends BroadcastReceiver{

    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    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]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

Note: In your manifest file add the BroadcastReceiver-

<receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add this permission:

<uses-permission android:name="android.permission.RECEIVE_SMS" />

also you build notification by using the Notification.Builder

Upvotes: 3

NKijak
NKijak

Reputation: 1172

Broadcast receiver will be invoked by android as long as you have it properly registered (either via code or in your manifest xml). You will be given access to a context in the receiver callbacks. From that context you can either create a Notification (based on the title of this question) or access applicationContext which would be your Application subclass IF you declared one in your manifest xml.

Upvotes: 0

If I were you I would put an intent call in the onReceive method of the broadcast receiver to which you pass a bundle value and then on the mainactivity look to see if that bundle exists and if so do whatever action you wish to do (e.g. show a dialog, toast, etc.).

Upvotes: 0

Related Questions