0

I want to pass a function from one activity to another using Broadcasts. Like we can pass Strings and int by putExtra, Is there a way I can pass a whole function? I know there are other ways to do this, but I need to do this with the help of broadcasts. Any help?

Ex:

void myFunc(){ /* foo */ }

Can I use myFunc in some other activity via broadcast? I don't mind declaring the function again in the new activity as long as I get data from broadcast.

Derlin
  • 9,572
  • 2
  • 32
  • 53
Tejas Soni
  • 37
  • 8
  • 1
    have a look at https://stackoverflow.com/questions/45617564/is-there-a-way-to-pass-a-function-reference-between-activities it is basically what you are asking for (works the same in Kotlin and Java) – Derlin Jun 18 '18 at 12:15

1 Answers1

1

Is there a way I can pass a whole function?

No, sorry.

Can I use myFunc in some other activity via broadcast?

No, sorry.

Alternatives:

  • Use one activity rather than two

  • Have both activities work with some other object that is outside each of those activities (e.g., a singleton serving as a repository)

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Thank you for answering. Can I not do it with a serializable function? Or Somehow pass a String of my function ("void myFunc(){ /* foo */ }") and then somehow use this string to create the same function in the new activity? – Tejas Soni Jun 18 '18 at 12:35
  • @TejasSoni: "Can I not do it with a serializable function?" -- there is no such thing as a "serializable function" in Java or JVM-based languages. "Or Somehow pass a String of my function ("void myFunc(){ /* foo */ }") and then somehow use this string to create the same function in the new activity? " -- no, because Java is not an interpreted language. It is a compiled language, with the compiler being on your development machine. – CommonsWare Jun 18 '18 at 13:02