Android: calling Activity from BroadcastReceiver

This tutorial is a continuation of the previous post:
http://ukitech.blogspot.com/2014/11/android-sms-app.html

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

package com.chicagoandroid.android.app.sms;
import android.app.Application;
/**
 * Created by uki on 11/22/14.
 */
public class MyApplication extends Application {
   @Override
   public void onCreate() {
      super.onCreate();
   }
   /**
    * we use this class member to hold instance of our activity.
    */
   public MainActivity mainActivity;
}


Step: Declare it in the AndroidManifest.xml file

    <application
            android:name="com.chicagoandroid.android.app.sms.MyApplication"

Step: Pass Activity to Application

public class MainActivity extends ActionBarActivity {
...
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      etSmsTextSearch = (EditText) findViewById(R.id.sms_search_text);
      etSmsRespondSearch = (EditText) findViewById(R.id.sms_respond_text);
      smsReceived = (TextView) findViewById(R.id.sms_received);
      // keep reference to Activity context
      MyApplication myApplication = (MyApplication) this.getApplicationContext();
      myApplication.mainActivity = this;

   }


Step: In your BroadcastReceiver make sure you use Application Context

   @Override
   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();



As an Amazon Associate I earn from qualifying purchases.

My favorite quotations..


“A man should be able to change a diaper, plan an invasion, butcher a hog, conn a ship, design a building, write a sonnet, balance accounts, build a wall, set a bone, comfort the dying, take orders, give orders, cooperate, act alone, solve equations, analyze a new problem, pitch manure, program a computer, cook a tasty meal, fight efficiently, die gallantly. Specialization is for insects.”  by Robert A. Heinlein

"We are but habits and memories we chose to carry along." ~ Uki D. Lucas


Popular Recent Articles