22

All of us known we register BroadcastReceiver in two types

1)Static Registration

2)Dynamic Registration

But my doubt is when we need to use Static and when we need to use Dynamic?

Krishna
  • 343
  • 1
  • 2
  • 9
  • 1
    possible duplicate of [Broadcast Receiver Register in Manifest vs. Activity](http://stackoverflow.com/questions/10876015/broadcast-receiver-register-in-manifest-vs-activity) – nKn Apr 23 '14 at 10:45
  • 1
    http://www.vogella.com/tutorials/AndroidBroadcastReceiver/article.html check out this link. Static mostly used when you want to listen to an event all the time & dynamic may be used when one of the screen of your application is open and unregister that receiver once app is closed. – Gautami Apr 23 '14 at 11:14

5 Answers5

23

As we know there are two ways to register a BroadcastReceiver; one is static and the other dynamic.

Static:

  1. Use tag in your Manifest file. (AndroidManifest.xml)
  2. Not all events can be registered statically.
  3. Some events require permissions.

Dynamic:

  1. Use Context.registerReceiver() to dynamically register an instance.
  2. Note: Unregister when pausing.

When we are doing dynamic registration (i.e. at run time) it will be associated with lifecycle of the app. If we do it static registration (i.e. on compile time) and our app is not running, a new process will be created to handle the broadcast.

Sufian
  • 6,405
  • 16
  • 66
  • 120
Jitesh Upadhyay
  • 5,244
  • 2
  • 25
  • 43
8

1) Static Registration

Implementation are in manifest, android system can initiate processes and run your boardcast receiver. One example like you want to update your data when a new intent coming in from system or etc.. You need to take care Security issue as well.

2) Dynamic Registration

Implementation are in java code, boardcast receiver runs only when your app is running up to that registration line. Thus, you mostly want to use this if you only want to bring up the boardcast receiver with certain conditions.

  • Very important detail. Plus, with dynamic broadcasting, you will have the power of turning it on and off depending the lifecycle of your component. – stdout Oct 07 '16 at 06:58
7

Easiest way decide is:

If you want your App to listen the broadcast even if the App is closed Go for Static Broadcast Reciever.

If you want your App to listen only for certain instance(When App is running) then go for Dynamic BroadCast Receiver.

example:

Any Battery monitoring App needs to listen to all broadcast intents(related to battery) even if App is not running. So here we need Static

Any App that uses OTP, needs to listen to Sms only when App is running. Go for dynamic.

Puneet Verma
  • 1,373
  • 2
  • 19
  • 23
  • 1
    You cannot register receivers in the manifest for most implicit broadcasts (such as battery-related intents) on Android 8 and newer due to [https://developer.android.com/about/versions/oreo/background#broadcasts](background execution limitations). – mike47 Apr 29 '19 at 10:24
2

I am going to show you difference static and dynamic broadcast receivers via coding:

a) Define UI for both kind of receviers:

     <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.broadcastreceiverdemo.MainActivity">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="registerBroadcastReceiverDynamically"
            android:text="Register Broadcast Receiver Dynamically" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="sendUsingDynamicallyRegisteredBroadcastReceiver"
            android:text="Send Broadcast Msg Dynamically" />
    </LinearLayout>


    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:onClick="sendUsingStaticallyRegisteredBroadcastReceiver"
        android:text="Send Broadcast Statically"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

b) DynamicBroadcastReceiver.java

 public class DynamicBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Dynamic Broadcast", Toast.LENGTH_SHORT).show();
}

}

c) StaticBroadcastReceiver.java

public class StaticBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Toast.makeText(context, "Static Broadcast", Toast.LENGTH_SHORT).show();
}

}

d) MainActivity.java

 public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
//////////////////=================Starts Dynamic Broadcast Receiver
DynamicBroadcastReceiver dynamicBroadcastReceiver = new DynamicBroadcastReceiver();

public void registerBroadcastReceiverDynamically(View view) {
    IntentFilter filter = new IntentFilter();
    filter.addAction("MY_BROADCAST");
    registerReceiver(dynamicBroadcastReceiver, filter);
}

public void sendUsingDynamicallyRegisteredBroadcastReceiver(View view) {
    Intent i = new Intent();
    i.setAction("MY_BROADCAST");
    sendBroadcast(i);
}

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

//////////////////=================Ends Dynamic Broadcast Receiver


//////////////////=================Starts Static Broadcast Receiver
public void sendUsingStaticallyRegisteredBroadcastReceiver(View view) {
    Intent i = new Intent();
    i.setAction("MY_BROADCAST_STATIC");
    sendBroadcast(i);
}

}

e) Manifest File:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.broadcastreceiverdemo">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".DynamicBroadcastReceiver">

        </receiver>
        <receiver android:name=".StaticBroadcastReceiver">
            <intent-filter>
                <action android:name="MY_BROADCAST_STATIC" />

            </intent-filter>
        </receiver>
    </application>

</manifest>
0

If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts. Except these broadcasts. the android system package manager register static broadcast receivers when the app is installed and opened first time. dynamic broadcast receivers are tied to application life cycle. we should unregister them in onDestroy to avoid memory leaks.

Ehsan souri
  • 181
  • 3
  • 7