Siluni Pathirana
Siluni Pathirana

Reputation: 429

Calling Main activity method in broadcastReceiver

I want to show a notification generate from my app when new specific sms comes. so notification generation method is in my main activity.when new income message comes i have to generate the notification. This is my BroadcastReceiver class.

public class BroadCastReceiver extends BroadcastReceiver{ //private AudioManager myAudioManager;

public MainActivity mainactivity = null;

public BroadCastReceiver() {
}

public void setMainactivityHandler(MainActivity mainn){
   this.mainactivity = mainn;
}



@Override
public void onReceive(Context context, Intent intent) {



    if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED") )
    {
        Toast.makeText(context, "SMS_RECEIVED", Toast.LENGTH_LONG).show();
        System.out.println("received sms");

        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Log.i("cs.fsu", "smsReceiver : Reading Bundle");

            Object[] pdus = (Object[])bundle.get("pdus");
            SmsMessage sms = SmsMessage.createFromPdu((byte[])pdus[0]);

            if(sms.getMessageBody().contains("aa")) {
                abortBroadcast();
                System.out.println("received correct");
                Log.e("tag", "corecttttttttttttttttttttttttttttttttttttttttttt");
                Toast toast = Toast.makeText(context, "BLOCKED Received SMS: ", Toast.LENGTH_LONG);
                toast.show();
                mainactivity.showNotification();
                abortBroadcast();






            }}
    }


}

}

This is my main activity

public class MainActivity extends Activity {

public BroadCastReceiver Br = null;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Br = new BroadCastReceiver();
    Br.setMainactivityHandler(this);
    IntentFilter callInterceptorIntentFilter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    registerReceiver(Br,  callInterceptorIntentFilter);


    // listener handler
    View.OnClickListener handler = new View.OnClickListener(){
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btnShowNotification:
                    showNotification();
                    break;

                case R.id.btnCancelNotification:
                    cancelNotification(0);
                    break;
            }
        }
    };

    // we will set the listeners
    findViewById(R.id.btnShowNotification).setOnClickListener(handler);
    findViewById(R.id.btnCancelNotification).setOnClickListener(handler);

}


public void showNotification(){

    Log.e("","show notification");
    // define sound URI, the sound to be played when there's a notification
    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    // intent triggered, you can add other intent for other actions
    Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
    PendingIntent pIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);

    // this is it, we'll build the notification!
    // in the addAction method, if you don't want any icon, just set the first param to 0
    Notification mNotification = new Notification.Builder(this)

            .setContentTitle("New Post!")
            .setContentText("Here's an awesome update for you!")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .setSound(soundUri)

            .addAction(R.drawable.ic_launcher, "View", pIntent)
            .addAction(0, "Remind", pIntent)

            .build();

    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // If you want to hide the notification after it was selected, do the code below
    // myNotification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, mNotification);
}

public void cancelNotification(int notificationId){

    if (Context.NOTIFICATION_SERVICE!=null) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(notificationId);
    }
}

}

when new message come it give this error

07-29 22:06:59.227  23021-23021/com.example.siluni.myapplication E/tag﹕ corecttttttttttttttttttttttttttttttttttttttttttt

07-29 22:06:59.267 23021-23021/com.example.siluni.myapplication D/AndroidRuntime﹕ Shutting down VM 07-29 22:06:59.277 23021-23021/com.example.siluni.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.siluni.myapplication, PID: 23021 java.lang.RuntimeException: Unable to start receiver com.example.siluni.myapplication.BroadCastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.siluni.myapplication.MainActivity.showNotification()' on a null object reference

Upvotes: 0

Views: 1772

Answers (1)

Smit.Satodia
Smit.Satodia

Reputation: 597

This is because when your broadcast receiver executes your MainActivity's method, then might be chances that your activity is not running or not even starts, so this kind of problem occurs.

How to solve:

  1. Create one global class.
  2. Made your showNotification method public static there, if you want then pass the context. 3.just call it from main activity as well in broadcast receiver.

If you are unable to make static method, then just create object of that global class, and call that method using object.

Tell me if you face any problem while implementing this.

Upvotes: 1

Related Questions