java - Calling MainActivity method from other classes (which extend broadcast receiver) -
i'm trying call method display_notification of mainactivity other class (phonestatereceiver).
but got error:
java.lang.runtimeexception: unable start receiver com.weekendproject.roshu.spamblocker.phonestatereceiver: java.lang.nullpointerexception: attempt invoke virtual method 'java.lang.string android.content.context.getpackagename()' on null object reference
error specially pointed line in mainactivity
intent resultintent = new intent(getapplicationcontext(), mainactivity.class);
however tried change getapplicationcontext()
"this"
, "getactivity()"
, not working
here complete code
mainactivity.java
public class mainactivity extends actionbaractivity { public void display_notification(string incoming_number) { notificationcompat.builder mbuilder = new notificationcompat.builder(getapplicationcontext()) .setsmallicon(r.drawable.ic_action) .setcontenttitle("spamblocker alert !!") .setcontenttext("spamblocker blocked number : " + incoming_number); // **error occured in following line** intent resultintent = new intent(getapplicationcontext(), mainactivity.class); taskstackbuilder stackbuilder = taskstackbuilder.create(getapplicationcontext()); stackbuilder.addparentstack(mainactivity.class); stackbuilder.addnextintent(resultintent); pendingintent resultpendingintent = stackbuilder.getpendingintent( 0, pendingintent.flag_update_current ); mbuilder.setcontentintent(resultpendingintent); notificationmanager mnotificationmanager = (notificationmanager) getsystemservice(context.notification_service); random r = new random(); int rand = r.nextint(1000); mnotificationmanager.notify(rand, mbuilder.build()); } }
phonestatereceiver.java
public class phonestatereceiver extends broadcastreceiver { mainactivity mactivity; @override public void onreceive(context context, intent intent) { mactivity = new mainactivity(); mactivity.display_notification(incomingnumber); // call main activity methods } }
you not using context provided onreceive. try passing context display_notification rather using activity's context might not running @ time receive broadcast.
so change method signature this:
public void display_notification(string incoming_number, context context)
and, pass context onreceive this:
mactivity.display_notification(incomingnumber, context);
and use context when pass intent this:
intent resultintent = new intent(context, mainactivity.class);
edited
either put entire method in receiver , use context provided onreceive
or,
change line this:
notificationmanager mnotificationmanager = (notificationmanager) context.getsystemservice(context.notification_service);
important part is, context.getsystemservice, context onreceive.
Comments
Post a Comment