Reputation: 11
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.
Upvotes: 1
Views: 3536
Reputation: 18222
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
Upvotes: 0
Reputation: 24031
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.
Upvotes: 1