Home > database >  Communication between Library and App in Android
Communication between Library and App in Android

Time:04-13

I'm developing a native android SDK that theoretically could be integrated in various apps.

I need the SDK to be able to notify the App that integrates it when some conditions are verified. I don't need to send a text or some kind of result, I'd simply need a way to send a notification. That's why I thought to achieve this objective using by sending in the library and configuring a BroadcastReceiver in the app. However, since this SDK should be App-independent i can't put the name of MainActivity in the intent.

So, I'm thinking I could use a Messenger, but I'm not sure if I understood correctly how it should work. As far as I understood, my sdk should expose a method like:

provideHandler(Handler h)

through which the app could provide an Handler. With such Handler, I could istantiate a Messenger object and send a message to the app by using the sendMessage method of my Messenger. I'm wondering if this is a correct approach, or which would be a correct approach for my use case.

CodePudding user response:

The good thing about libraries, is their code is included in the app's that depend on them. So you can use normal callback mechanisms to communication.

No need for IPC, or BroadcastReceivers or Handlers etc.

Here is a simple starter:

Library:

interface MyListener {
    fun callbackThis()
}

class Library {

    var listener: MyListener? = null
    
    fun setListener(listener: MyListener) {
        this.listener = listener
    }

    fun stuffGetsDone() {
        // do your library stuff
        // call the app
        listener?.callbackThis()
    }

}

My App:

val yourLibrary = Library()

yourLibrary.setListener(object: MyListener() {
    override fun callbackThis() {
       // This is in your app, but called from the library
    }
})
  • Related