1

I am currently developing an app, I need to call an activity method from BroadcastReceiver.

My app is to when the user getting a call Broadcast receiver find that and send a message to that particular number.

I am able to get that no, but I want to send a message to that number, for this sending sms I created an activity in side sending sms method is there..

How do I call that particular method from my BroadcastReceiver.

ashok
  • 11
  • 1
  • 2
  • 1
    what if your activity is closed? – Sherif elKhatib Sep 21 '11 at 06:56
  • 1
    yeah...bad practice. better use a Service or put the receiver in your activity – Ovidiu Latcu Sep 21 '11 at 07:08
  • I figuer it , see this link : [Call an activity method from a BroadcastReceiver class][1] and : [Call an activity method from a BroadcastReceiver. Is it possible?][2] [1]: http://stackoverflow.com/questions/16934425/call-an-activity-method-from-a-broadcastreceiver-class [2]: http://stackoverflow.com/questions/5104235/call-an-activity-method-from-a-broadcastreceiver-is-it-possible?rq=1 – Adnan Abdollah Zaki Mar 14 '14 at 15:28

2 Answers2

1

You need to make that method static and public inside your activity.You can call that method like this:

ActivityName.mehtodName();

It will be much better if you put that method in your util class and call it from there.

Vineet Shukla
  • 23,865
  • 10
  • 55
  • 63
0

You can create a Callback using an interface for calling that the activity method from BroadcastReceiver

interface MyCallback{

      public void doStuff();

}

Provide the CallBack in the BroadcastReceiver

public class MyBroadcastReceiver extends BroadcastReceiver{

   private MyCallback callback;

   public MyBroadcastReceiver(MyCallback callback){

       this.callback = callback;          //<-- Initialse it

   } 

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

       callback.doStuff();                //<--- Invoke callback method
   }

}

Now implement the Callback in your Activity and override the method

MyActvity extends AppcompatActivity implements MyCallback {

   // Your Activity related code //
   // new MyBroadcastReceiver(this);    <-- this is how you create instance

   private void sendSMS(){
     // your logic to send SMS
   } 


   @Override 
   public void doStuff(){
     sendSMS();          //<--- Call the method to show alert dialog
   }

}

You can read the advantage of using this approach here in detail

Rohit Singh
  • 16,950
  • 7
  • 90
  • 88