2

I have an activity (Activity_A) that has a handler and is receiving messages from an external library. The problem is that Activity_A launches activity Activity_B. When Activity_B is launched, Activity_A receives a message on the handler that I want to "send" to Activity_B.

How to do that?

I cannot move the handler from Activity_A to Activity_B as some of the messages that receives have to be managed by Activity_A.

I would like to avoid using global/static variables. Is it possible to somehow save in Activity_A a reference to Activity_B when I create the intent? How to send a message from Activity_A to Activity_B ?

An important point here is that, yes, I want to pass an object from one activity to another, but not in the moment I create the new activity (passing the object in a bundle). I want to do it asynchronously, whenever I receive a message from an external library.

steve_patrick
  • 735
  • 2
  • 9
  • 19
  • You should consider a complete different approach. Your activity A might be killed completely when you start activity B. Instead of a handler that receives something, you might want to consider a broadcast receiver that handles/listens to specific intents (which are nearly the same as messages)? – WarrenFaith Apr 15 '13 at 11:37

2 Answers2

9

In Activity_A

String msg = "message";
Intent i = new Intent(Activity_A.this, Activity_B.class);
i.putExtra("keyMessage", msg);
startActivity(i);

In Activity_B

Bundle extras = getIntent().getExtras();
String msg = extras.getString("keyMessage");

Hope it's help.

UPDATE:
I described the process of interaction of two Activities. But if message arrived from library, when Activity_B run - this method is not relevant.
Try to move handler to some Service, which will work when you will need to. And from Activity_A and Activity_B you can periodically inquire service "came a new message?" using Timer.

jimpanzer
  • 3,470
  • 4
  • 44
  • 84
0

Application can't work that way. If you want activity to make some job it must be visible to user. You can consider Service to do background jobs (i.e. sensor handling), or make Activity B fragment - then actibity A will be still in foreground while it's fragment is visible to user.

piotrpo
  • 12,398
  • 7
  • 42
  • 58