Search code examples
androidnullpointerexceptionbroadcastreceiversms

Broadcast receiver for sms is invoked even it is unbound


I am creating an app in which i am using broadcast receiver to get the content of the coming message.I am using an interface to implement the broadcast receiver binding and unbinding.This is already implemented in my another app.There it works fine,but in current app ,app crashes if the activity is stopped or destroyed which gives the following error

Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'void com.encureit.a24klen.interfaces.SmsListerner.messageReceived(java.lang.String)' on a null object reference

Here is my broadcast receiver class code:

public class SmsReceiver extends BroadcastReceiver {
private static SmsListerner smsListener;
@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle=intent.getExtras();

    Object []pdus= (Object[]) bundle.get("pdus");

    for (int i=0;i<pdus.length;i++){
        SmsMessage smsMessage=SmsMessage.createFromPdu((byte[]) pdus[i]);

        String messagBody=smsMessage.getMessageBody();
        if (messagBody.contains("Password")){
            smsListener.messageReceived(messagBody);
        }
    }

}

public static void bindListner(SmsListerner listener){

    smsListener=listener;
}

public static void unBindListener(){
    smsListener=null;
}
}

I am calling these methods in my activity's onresume()

  @Override
protected void onResume() {
    super.onResume();
    SmsReceiver.bindListner(new SmsListerner() {
        @Override
        public void messageReceived(String messageText) {
            String msg=messageText;
            if (msg.contains("data")){

               //string operations
            }

        }
    });
}

and in onDestroy

 @Override
protected void onStop() {
    super.onStop();
    SmsReceiver.unBindListener();

}

Message comes and everything works fine but when app is in background it crashes.Please help me regarding this .Thanks in adavance


Solution

  • sure thing, when you stop the activity the smsListener become null there for it will crash if you don't want anything to happend when the activity is stoped add this

     if (messagBody.contains("Password")&&smsListener!=null){
                smsListener.messageReceived(messagBody);
            }