I have an app with an activity sending a broadcast to another activity. Everything appears to be fine. But if I close my app and open it again, this broadcasts seems to get send more than once. In fact it gets send as often I reopened the app. If I print out "Activity.this" right before sending the broadcast I get different instances.
Why could this happen? Why is the activity not dying? I checked, onDestroy get's called. BUT I have a background-service, which I dont stop, when the app is closed. Is it therefore? Can I reopen the old activity, when starting the app instead of opening a new one?
Setting launchmode in the Manifest to singleTask or singleInstance didn't work either.
EDIT Even using an AtomicInteger like in the second answer here Prevent multiple instances of my Android application composed of a single activity didn't work.
Thanks!
Edit:
I got a broadcast receiver in the ClientActivity (main) like that, coming from my service. Here I send a broadcast to another Activity (MessageActivity).
private BroadcastReceiver serviceMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("test", ClientActivity.this.tostring();
sendToMessageActivity(newDBMessageStr, "updateMessageList");
}
};
private void sendToMessageActivity(String message, String putExtra)
{
Intent intent = new Intent("de.blabla.bla.sendToMessageActivity");
sendLocationBroadcast(intent, message, putExtra);
}
private void sendLocationBroadcast(Intent intent, String message, String putExtra)
{
intent.putExtra(putExtra, message);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}
I registered this in the onCreate-Method of the ClientActivity:
LocalBroadcastManager.getInstance(this).registerReceiver(
serviceMessageReceiver, new IntentFilter("de.blabla.bla.serverMessage"));
The Other activity called "MessageActivity" which gets the broadcast from the ClientActivity (main), as described above registers the following in its onCreate:
LocalBroadcastManager.getInstance(this).registerReceiver(
mainMessageReceiver, new IntentFilter("de.freshD.crapapp.sendToMessageActivity"));
Later it receives the message here:
private BroadcastReceiver mainMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
...
}
};
EDIT:
@Override
protected void onPause() {
super.onPause();
}
@Override
public void onDestroy()
{
try
{
unregisterReceiver(serviceMessageReceiver);
}
catch (Throwable e) //IOException e
{
Log.d(logtag, "...Error data send: " + e.getMessage() + "...");
}
super.onDestroy();
}
Ohh when onPause is called, I need to unregister the Receiver there?
I edited onPause like this: (it didn't fix the bug)
@Override
protected void onPause() {
try
{
unregisterReceiver(serviceMessageReceiver);
}
catch (Throwable e) //IOException e
{
Log.d(logtag, "...Error data send: " + e.getMessage() + "...");
}
super.onPause();
}