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

No comments:

Post a Comment