Search code examples
javaandroidtcpondestroyapplication-close

How can i do something before app is closed?


I have made an App in android in which i have a TCP Client but now i want to send a message to the server only when the app is going to be closed, i've trying to add the openConnection (opening connection with TCP Client) and sendMessage (Sending message to the TCP server) action in onDestroy method but that didn't worked. The TCP Client i've used is in this guide, actually i need to send this message for communicate the server that the communication with the device is closed and send message "Device is Offline" and just then close the app.


Solution

  • Method 1: You can use ActivityLifecycleCallbacks to achieve this. There's an example with some logs below.

    public class MyApplication extends Application {
    
        private static final String TAG = MyApplication.class.getSimpleName();
        private int mVisibleCount;
        private boolean mInBackground;
    
        @Override public void onCreate() {
            super.onCreate();
            registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
                @Override public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                }
    
                @Override public void onActivityStarted(Activity activity) {
                    mVisibleCount++;
                    if (mInBackground && mVisibleCount > 0) {
                        mInBackground = false;
                        Log.i(TAG, "App in foreground");
                    }
                }
    
                @Override public void onActivityResumed(Activity activity) {
                }
    
                @Override public void onActivityPaused(Activity activity) {
                }
    
                @Override public void onActivityStopped(Activity activity) {
                    mVisibleCount--;
                    if (mVisibleCount == 0) {
                        if (activity.isFinishing()) {
                            Log.i(TAG, "App is finishing");
                        } else {
                            mInBackground = true;
                            Log.i(TAG, "App in background");
                        }
                    }
                }
    
                @Override public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
    
                }
    
                @Override public void onActivityDestroyed(Activity activity) {
                }
            });
        }
    
        public boolean isAppInBackground() {
            return mInBackground;
        }
    
        public boolean isAppVisible() {
            return mVisibleCount > 0;
        }
    
        public int getVisibleCount() {
            return mVisibleCount;
        }
    }
    

    Method 2: There's another method using Service to detect if application is terminated. See link