Lab Description:
Broadcast is an important component in Android. The processes can be communicated by broadcast. When intent is coming, service will send a broadcast intent. It can be picked up by a BroadcastReceiver, and then get data from intent.
How to send broadcast?
/*We use function sendBroadcast(Intent intent), which gives intent to all interested BroadcastReceivers. */
Code:
private static final String MY_ACTION = "com.prgguru.android2.MAIN";
Intent intent = new Intent();
intent.setAction(MY_ACTION);
sendBroadcast(intent);
How to receive?
First, register broadcast. There are two methods to register broadcast: the first method is that we can register it in the manifest XML file; the other is dynamic registration in the code. When we use first method, the broadcast cannot be stopped even the activity stops. The activity’s death or live will not affect the broadcast receiver. The second method will affect.
Code in AndroidManifest.xml(first method):
<intent-filter>
<action android:name="com.prgguru.android2.MAIN"/>
</intent-filter>
Code in Java:
public class broadcast2Activity extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setClass(context, DisplayActivity.class);
context.startActivity(i);
}
}
Example:
There are two processes in the emulator. They communicate with broadcast. The first process is a sender, and the other is receiver which runs background. When user click button send broadcast, the receiver will listen to the broadcast and then make a notification in the top of android phone. After seeing the notification, you can click cancel button to clear this notification and it will invoke sender program. We need to run receiver program at first. Then run sender program.
In order to help you understand, the relation graph is following:
General graph
Detailed graph
Emulator Screen shot:
Step 1: the receiver will be run at first. It will be run in background. And we can see it in the console window.
Step 2: the sender will be run. Click Button(send brandcast), send broadcast, and then kill itself.
When receiving a message, there will be a notification text displayed above the button: "test notification".
Step 3: click button, cancel notification, kill itself return to step one.(screen shot is same to the step 1)
Sender code:
Step 1: make a project.
Android version: 2.2
Step 2: modify the androidManifest.xml , main.xml and MainActivity.java
AndroidManifest.xml
<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <activity android:name=".MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="com.prgguru.android.MAIN"/> <action android:name="android.intent.action.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity></application>Main.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:text="Send Broadcast" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button></LinearLayout>MainActivity.java
import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;/** * Example send broadcast */public class MainActivity extends Activity { // initial Button private Button btn; // Define Broadcast Receiver action private static final String MY_ACTION = "com.prgguru.android2.MAIN"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Button btn = (Button)findViewById(R.id.Button01); // add listener btn.setOnClickListener(listener); } private OnClickListener listener = new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(MY_ACTION); sendBroadcast(intent); finish(); // kill itself } };}Receiver Code:
Step 1: make a new project for receiver(Android Version: 2.2)
Step 2: modify the AndroidManifest.xml
We add "<activity android:name="DisplayActivity"/>" to display the notification text and a receiver to listen to the incoming broadcast.
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.prgguru.android2" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <receiver android:name=".broadcast2Activity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <intent-filter> <action android:name="com.prgguru.android2.MAIN"/> </intent-filter> </receiver> <activity android:name="DisplayActivity"/> </application></manifest>Step 3: broadcast2Activity.java code
import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.widget.Toast; public class broadcast2Activity extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Intent i = new Intent(); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); i.setClass(context, DisplayActivity.class); context.startActivity(i); }}Step 4: main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".ReceiverActivity" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignParentTop="true"
android:layout_marginTop="22dp"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/textView1"
android:layout_marginLeft="16dp"
android:layout_marginTop="29dp"
android:text="Cancel Notification" />
</RelativeLayout>
Step 5: create a class(DisplayActivity). DisplayActivity.java code
im1port android.app.Activity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button; public class DisplayActivity extends Activity { private Button cancelBtn; private Notification n ; private NotificationManager nm; // Notification's ID private static final int ID = 1; Intent intent = new Intent(); private static final String MY_ACTION = "com.prgguru.android.MAIN"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView txt=(TextView) findViewById(R.id.textView1);
txt.setText("test notification");
// initial button cancelBtn = (Button)findViewById(R.id.Button02); // get NotificationManager instance String service = NOTIFICATION_SERVICE; nm = (NotificationManager)getSystemService(service); // get Notification n = new Notification(); // set notification icon int icon = n.icon = R.drawable.ic_launcher; // set notification text String tickerText = "Test Notification"; // display time long when = System.currentTimeMillis(); n.icon = icon; n.tickerText = tickerText; n.when = when; intent.setAction(MY_ACTION); PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0); n.setLatestEventInfo(this, "My Title", "My Content", pi); // send notification nm.notify(ID, n); // add listener cancelBtn.setOnClickListener(cancelListener); } // content of listener private OnClickListener cancelListener = new OnClickListener() { @Override public void onClick(View v) { // cancel notification nm.cancel(ID); // startActivity(intent); finish(); } };
}