poveda
poveda

Reputation: 1

Different behavior when App is sent to Background State using Home or Back physical button

I'm testing in Android a chat app developed in React Native and I'm noticing a strange behavior that only depends on how do you send the app to background.

Two devices are needed to replicate the bug: Device1 with User1 logged in and Device2 with User2 logged in.

Case situation:

  1. Send App from Active to Background state using the Home button.
  2. Send App from Active to Background state using the Back physical button.

Once the App in Device1 is on Background State, wait for 1-2 minutes until de WebSocket connection is closed. Then, send a chat message from User2 to User1. Open the App again in Device1 (changing its state to Active)

In case 1, you will receive the message correctly and you'll see the message sent in the Chats view as well as inside the conversation. In case 2, the reception of the message is inconsistent. You may receive it, but it will not show in the Chats view, and inside the conversation it will appear with the wrong order and/or timestamp.

Upvotes: 0

Views: 773

Answers (3)

Omegalen
Omegalen

Reputation: 1496

As others have mentioned, the back button ends up killing the activity to free resources. While there is no way to guarantee that the Android OS will not kill your activity, you can change the back button's default behavior to not kill the activity by adding this code to your MainActivity class:

@Override
public void invokeDefaultOnBackPressed() {
    // do not call super. invokeDefaultOnBackPressed() as it will close the app.
    // Instead lets just put it in the background.
    moveTaskToBack(true);
}

Upvotes: 0

AlexTa
AlexTa

Reputation: 5251

That's due to application's (activity) life cycle:

a) When you press home button, onStop() method is called but not onDestroy(), so your application is still alive until OS needs resources and it will destroy it and this is why is working for you in this case.

b) When you press back button, onStop() method is call but also onDestroy(), so your application is inmediately destroyed, a this why is not working for you in this case.

Upvotes: 1

CodingRat
CodingRat

Reputation: 1944

Answer to your question sounds very simple but in real to solve the problem it need extra handling.

1) When User press home button app goes in background the activity is alive and OS will kill whenever it need resources.

2) When User press hardware back button OS kills the activity and free resources.

You can solve you problem by using below approach.

You need to listen message in services and store them in local storage and update UI only if available.

Upvotes: 0

Related Questions