January 2013
Intermediate to advanced
408 pages
9h 23m
English
In Android, a broadcast enables you to send a message to another part of your application (or another application) so that you can inform it of something happening. In this recipe, you learn how to create a broadcast receiver to listen for broadcasts, as well as send broadcasts to other applications.
There are two ways to create a broadcast receiver: programmatically through code and declaratively via the AndroidManifest.xml file. The following sections address each possible solution.
Consider the following activity:
package net.learn2develop.usingbroadcastreceiver;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
MyBroadcastReceiver myReceiver;
IntentFilter intentFilter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new MyBroadcastReceiver();
intentFilter = new IntentFilter("MY_SPECIFIC_ACTION");
}
@Override
public void onResume() {
super.onResume();
//---register the receiver---
registerReceiver(myReceiver, ...Read now
Unlock full access