Suggested Pages

Monday, April 13, 2015

BroadcastReceiver Android Example


BroadcastReceiver Android Example



In the following snippets of code you can see an example of BroadcastReceiver. A BroadcastReceiver is a component that acts as listener of of events that could be publish by a component that acts as a Publisher. In the example I use the Context as a publisher.

Step-1: Create a class that extends BroadcastReceiver

CommandReceiver


public class CommandReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  
                String action = intent.getAction();

                if(action.equals(Command.SHOW)){
                   String textMessage=intent.getStringExtra(Command.VALUE);
                   Toast.makeText(context,textMessage, Toast.LENGTH_SHORT).show();
                }
              
 }
}   
   
]]>

Command.java


public interface Command {

    public static final String SHOW="SHOW";

    public static final String VALUE="VALUE";

}
  

Step-2: Declare the receiver int AndroidManifest.xml

AndroidManifest.xml


      <receiver
            android:name="package.CommandReceiver "
            android:enabled="true"
            android:exported="false" >
        </receiver>
  

Step-3: Register the receiver in your Activity

ActivityExample


public class ActivityExample extends Activity {

 private CommandReceiver commandReceiver;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
                commandReceiver=new CommandReceiver();
         registerReceiver(commandReceiver, new IntentFilter(Command.SHOW));
 }


 @Override
 protected void onDestroy() {
  super.onDestroy();
  if(commandReceiver!= null) {
      unregisterReceiver(commandReceiver);
  }
 }
}
  

Step-4: Publish the Intent

Publisher Example

  
          Intent event = new Intent(Command.SHOW);
   event.putExtra(Command.VALUE, "MESSAGE");
   Context applicationContext = getApplicationContext();
   applicationContext.sendBroadcast(event);

No comments :

Post a Comment

Suggested Pages