Sending & Receiving Custom Broadcasts

Android system initiates many system-wide broadcast announcements such as screen turned off and battery is low broadcasts. Also, apps can initiate custom “defined by developers” broadcast. A broadcast is a way to send a message within an application or another application. A BroadcastReceiver is a component that listens and responds to the initiated broadcasts. In this post, we will see how to send custom broadcast and how to declare a broadcast receiver programmatically and using Manifest file to listen to this broadcast.

 

 

Objectives:

  • How to send a broadcast?
  • How to create a broadcast receiver sub class?
  • How to register the receiver in Java code or in manifest file?

Environment & Tools:

  • Android Developer Tools (ADT) (or Eclipse + ADT plugin)
  • AVD Nexus S Android 4.3 “emulator”
  • Min SDK 8

( 1 ) Create Layout “UI”

  • res/layout/activity_main.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<LinearLayout 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"
    android:orientation="vertical"
    tools:context=".MainActivity" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:text="Received Broadcasts" />
    <Button
        android:id="@+id/btnSendBroadcast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:layout_gravity="center_horizontal"
        android:text="Send Broadcast"
        />
    <EditText
        android:id="@+id/etReceivedBroadcast"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>

( 2 ) Extend BroadcastReceiver

  • Create a subclass extending BroadcastReceiver call it MyReceiver.
  • Override onReceive() method to print intent action name on the EditText
  • /src/com/hmkcode/android/MyReceiver.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.hmkcode.android;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
         MainActivity mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity;
         mainActivity.etReceivedBroadcast.append("broadcast: "+intent.getAction()+"\n");
    }
    
}

( 3 ) Send Broadcast

  • To send a broadcast, create an Intent with action name and pass it to sendBroadcast()
Intent i = new Intent("com.hmkcode.android.USER_ACTION");
sendBroadcast(i);

( 4 ) Register BroadcastReceiver “Java or XML”

You can register the boradcast receiver dynamically in Java code or in the Manifest XML file.

  • In Java Code

  • Create instance of BroadcastReceiver class “MyReceiver” and instance of IntentFilter and pass them to registerReceiver() method.
  • Call registerReceiver() within Activity onResume() method.
@Override
    protected void onResume() {
        super.onResume();
        registerReceiver(new MyReceiver(), 
         new IntentFilter("com.hmkcode.android.USER_ACTION"));

    }
  • In Manifest XML File

  • Alternatively you can register the receiver in manifest file
1
2
3
4
5
<receiver android:name="com.hmkcode.android.MyReceiver" >
    <intent-filter>
        <action android:name="com.hmkcode.android.USER_ACTION" />
    </intent-filter>
</receiver>

( 5 ) Activity Class

  • /src/com/hmkcode/android/MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.hmkcode.android;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
    MyReceiver myReceiver;
    IntentFilter intentFilter;
    EditText etReceivedBroadcast;
    Button btnSendBroadcast;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast);
        btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);
        
        //keep reference to Activity context
        MyApplication myApplication = (MyApplication) this.getApplicationContext();
        myApplication.mainActivity = this;
        btnSendBroadcast.setOnClickListener(this);
        
        myReceiver = new MyReceiver();
        intentFilter = new IntentFilter("com.hmkcode.android.USER_ACTION");
    }
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(myReceiver, intentFilter);
    }
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(myReceiver);
    }
    
    
    @Override
    public void onClick(View view) {
        
        Intent intnet = new Intent("com.hmkcode.android.USER_ACTION");
        sendBroadcast(intnet);
    
    }
    
}

( 6 ) Manifest.XML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="utf-8"?>
    package="com.hmkcode.android"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:name="com.hmkcode.android.MyApplication"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.hmkcode.android.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <receiver android:name="com.hmkcode.android.MyReceiver" >
            <intent-filter>
                <action android:name="com.hmkcode.android.USER_ACTION" />
            </intent-filter>
        </receiver>
        
    </application>
</manifest>

NOTE: If you want to register the receiver using Manifest XML file remove onResume and onPausemethods from the MainActivity class

( 7 ) Get Activity Context Workaround

When we register receiver using XML the system passes ReceiverResctrictredContext to onReceive() method. To get access to the MainActivity context in order to print on the EditText “etReceivedBroadcast” we need to workaround by extending our own Application class that holds reference to our MainActivity class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.hmkcode.android;
import android.app.Application;
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
    }
    
    MainActivity mainActivity;
    
}

Notice we used MyApplication in the Manifest file

<application
        android:name="com.hmkcode.android.MyApplication"

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s