Sharing Data between Modules in Dynamic Feature
Hello Everyone, In this article we will be discussing about sharing data between an application and DF(Dynamic feature) module. Throughout this article, I will be referring Dynamic Feature Module as DFM.
Let’s Get started.
Let me be more clear, In DFM we won’t be able to share resource between two DFM unless you use concepts like reflections. Here, we will be using an Broadcast Receiver to transfer intents between an application module to DFM or between two DFM’s.
Broadcast Sender Logic
So what are we doing here,
Declare an intent. Set the package name(if you ignore this the broadcast might fail in few Android N+ devices), data and action. Send the broad cast.
// init the intent
val intents = Intent()
// whatever you do don't skip this line
intents.setPackage(packageName)
// getting data from the intent and setting it to the intent
intents.putExtra("SEND", editText.text.toString())
// configuring the action(This action should be defined in the intent-filter)
intents.action = "SEND_DATA"
// TADA send the data
sendBroadcast(intents)
Broadcast Receiver Logic
The action defined before should be same as the action used in the intent filter else this won’t work.
AndroidManifest.xml
<application>
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="SEND_DATA" />
</intent-filter>
</receiver>
</application>
MyReceiver.kt(Broadcast Receiver Class)
Just receive the data and you are all set to go……🔥🔥🔥
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
// This method is called when the BroadcastReceiver is receiving an Intent broadcast.
Toast.makeText(context,intent.getStringExtra("SEND"),Toast.LENGTH_SHORT).show()
}
}
Issue ⚠️
Well, oops there is an issue in this process. Actually it’s a bug on intent-filter using DF.
When you send the data in the broadcast, it will send twice though you have send it only once. You can notice this in Android N+ devices. Feel free to use this, as this doesn’t impact the performance much. Just be aware you will receive two data’s. Meantime we can wait for the Google Guys to fix and save us.
Thank you.