Search code examples
androidmultithreadingsocketsterminate

How to properly terminate Android application with live sockets


I implemented an Android Application with following features:

Application: public class ApplicationGlobalAgent extends Application contains:

  • a MainActivity: to display GUI drawing -> and start other activities from it.
  • a network ServerSocket and a client Socket: to send/receive data in duplex mode.

I want to terminate Application when MainActivity finish, I did as follow:

In MainActivity extends Activity:

@Override
public void finish()
{
    super.finish();

    Log.d(DEBUG_TAG, "finish and call app termination");

    //call the application to terminate
    getApplication().onTerminate(); 
}

In ApplicationGlobalAgent extends Application:

@Override
public void onTerminate()
{
    // do close ServerSocket and client Socket in networking threads
    mNetworkManager.DoStop();

    System.gc();

    Log.d(DEBUG_TAG, "Terminated!");

    super.onTerminate(); //?? should be placed at the end of functions ??

    //totally kill this application process
    android.os.Process.killProcess(android.os.Process.myPid());
}

BUT results are:

When have no network connection, the application terminates successfully, otherwise "Terminated!" is never printed until I close the network sockets at other side (who connected to the Android sockets).

So, How can I force the application to properly and fully terminate when exit the MainActivity with connecting network sockets?

Appreciate all your helps!


Solution

  • @Override public void finish()

    You should be overriding onDestroy instead.

    getApplication().onTerminate();

    Never call this directly.

    System.gc();

    This really isn't necessary.

    android.os.Process.killProcess(android.os.Process.myPid());

    Why are you having the application call killProcess on itself? You should let the Android runtime system kill processes for you.

    How can I force the application to properly and fully terminate when exist the MainActivity with connecting network sockets?

    You don't need to worry about clean-up unless you have allocated resources that wouldn't be cleaned up when the Java process is killed by the kernel.