Communication between Modules in Android | Erselan Khan

Erselan Khan
Towards Dev
Published in
4 min readSep 16, 2022

Today we will show you how we can Communicate or Share Data between Modules in Android. But before moving forward, I would like to ask you to please follow my medium account to get the latest updates about Android and other tech-related topics.

What is Module or Modular Programming?

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

Want to check spelling mistakes on your documents? download Spelling Checker from the Play Store.

We generally use this approach in Android to develop features so we can easily use this module in another app to reuse the same code. If we use the Modular system in Android, we can also use the feature-on-demand built-in feature of Android to minimize our app size.

Communication between Modules:

There are two ways to communicate between Modules in Android:

  1. Using Callbacks/ Interfaces
  2. Using Local Broadcast

Using Callbacks/ Interfaces:

By using the Callbacks or Interface approach, we implement the interface methods on a high-level module and pass the data from low-level modules. Let’s assume that we have a Single Activity application which contains only one fragment i.e FirstFragment and an activity ie: MainActivity, we call this module as a high-level module. The second module contains one fragment i.e SecondFragment. Let’s start coding and see how we can implement this in Android:

We have a MainActivity that implement’s the SecondModuleNavigation, so we have to override its method. By overriding this method, we can easily share the data from Second Module to the First or Main Module:

class MainActivity : AppCompatActivity(), SecondModuleNavigation {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}

override fun shareDataFromSecondModule(data: String) {
toast(data)
}

}

fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

SecondFragment, which passes the data to the First or Main Module on button click:

class SecondFragment : Fragment() {

private lateinit var binding: FragmentSecondBinding

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentSecondBinding.inflate(inflater, container, false)
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setListener()
}

private fun setListener() {
binding.passData.setOnClickListener {
(requireActivity() as SecondModuleNavigation).shareDataFromSecondModule("Data From Second Module")

}
}
}

Callback or Interface for communication between the two modules:

interface SecondModuleNavigation {
fun shareDataFromSecondModule(data: String)
}

Using Local Broadcast:

Another approach is to use the local broadcast, we register the local broadcast on our activity creation and unregister the broadcast on our activity destruction.

MainActivity register’s the local broadcast on its creation and unregister’s the local broadcast on its destruction.

class MainActivity : AppCompatActivity(), SecondModuleNavigation {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
registerBroadcast()
}

override fun shareDataFromSecondModule(data: String) {
toast(data)
}

private fun registerBroadcast() {
LocalBroadcastManager.getInstance(this)
.registerReceiver(broadCastReceiver, IntentFilter(BROADCAST_FROM_THIRD_MODULE))
}

private fun unregisterBroadcast() {
LocalBroadcastManager.getInstance(this)
.unregisterReceiver(broadCastReceiver)
}

private val broadCastReceiver = object : BroadcastReceiver() {
override fun onReceive(contxt: Context?, intent: Intent?) {
when (intent?.action) {
BROADCAST_FROM_THIRD_MODULE -> {
toast(intent.getStringExtra(Constants.DATA) ?: "")
}
}
}
}

override fun onDestroy() {
unregisterBroadcast()
super.onDestroy()
}
}

fun Context.toast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}

object Constants {
const val BROADCAST_FROM_THIRD_MODULE = "data_from_third_module"
}

ThirdFragment, which passes the data to Main Module by using the intent on button click:

class ThirdFragment: Fragment() {

private lateinit var binding: FragmentThirdBinding

override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = FragmentThirdBinding.inflate(inflater, container, false)
return binding.root
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setListener()
}

private fun setListener() {
binding.passData.setOnClickListener {
val intent = Intent(BROADCAST_FROM_THIRD_MODULE)
intent.putExtra(DATA, "pass data from third module")
LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent)
}
}
}

object Constants {

const val DATA = "data"
const val BROADCAST_FROM_THIRD_MODULE = "data_from_third_module"
}

Project Github Link: https://github.com/arsalankhan994/module-communication

That’s it for now. I will cover more topics on Android, Java, Kotlin, and Springboot in my upcoming articles. If you like this article then Clap as much as you can 🤐

In case you missed: 🤐

  1. https://towardsdev.com/parallel-multiple-api-calls-or-network-calls-using-kotlin-coroutines-40cb5f313171
  2. https://towardsdev.com/kotlin-%EF%B8%8F-constructors-erselan-khan-984a5af2cac2
  3. https://medium.com/bazaar-tech/dynamically-update-refresh-reload-viewpager2-fragments-588fcbd6f859
  4. https://erselankhan.medium.com/the-story-behind-spelling-checker-app-erselan-khan-9ef09477b25d

Show your love by sharing this article with your fellow developers or Buy me a pizza by clicking this link https://www.buymeacoffee.com/erselankhan.

(Follow me for more content about Android, Kotlin, and other technologies. If you have any questions, go ahead and ask me here or email me at arsalankhan994@gmail.com and I’ll do my best to respond.)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Published in Towards Dev

A publication for sharing projects, ideas, codes, and new theories.

Written by Erselan Khan

Software Engineer | Android Developer | Kotlin | Springboot | Java | Technical Content Writer | Motivational Speaker

Responses (4)

What are your thoughts?