Saturday, November 22, 2014

Android: calling Activity from BroadcastReceiver

This tutorial is a continuation of the previous post:

We will learn how to connect Activity (UI) and BroadcastReceiver which does not know the Activity (and hence the UI) using Application class.

Step: create Application class

 * Created by uki on 11/22/14.
public class MyApplication extends Application {
   public void onCreate() {
    * we use this class member to hold instance of our activity.
   public MainActivity mainActivity;

Step: Declare it in the AndroidManifest.xml file


Step: Pass Activity to Application

public class MainActivity extends ActionBarActivity {
   protected void onCreate(Bundle savedInstanceState) {
      etSmsTextSearch = (EditText) findViewById(;
      etSmsRespondSearch = (EditText) findViewById(;
      smsReceived = (TextView) findViewById(;
      // keep reference to Activity context
      MyApplication myApplication = (MyApplication) this.getApplicationContext();
      myApplication.mainActivity = this;


Step: In your BroadcastReceiver make sure you use Application Context

   public void onReceive(Context context, Intent intent) {
         parser = new SmsParser(context);

Step: From Application Context get the Activity

   public SmsParser(Context context) {
      mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity;

Step: Form Activity you can call PUBLIC methods.

      String keyword = mainActivity.getSmsTextSearch();