Dynamic Registration vs Static Registration of BroadcastReceiver

17,370

Solution 1

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.

Solution 2

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.

Solution 3

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.

Solution 4

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>
Share:
17,370

Related videos on Youtube

Krishna
Author by

Krishna

Updated on June 03, 2022

Comments

  • Krishna
    Krishna about 2 years

    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?

  • stdout
    stdout over 7 years
    Very important detail. Plus, with dynamic broadcasting, you will have the power of turning it on and off depending the lifecycle of your component.
  • mike47
    mike47 about 5 years
    You cannot register receivers in the manifest for most implicit broadcasts (such as battery-related intents) on Android 8 and newer due to [developer.android.com/about/versions/oreo/… execution limitations).