Android: How to close foreground activity from active activity?

Niko Gamulin picture Niko Gamulin · Sep 28, 2009 · Viewed 10.9k times · Source

I created an application which is asynchronously communicating with the server. When the application makes a server request a new dialog (activity) with "loading" notification is created. The main activity implements methods for handling server responses and I would like to close the foreground activity when the main activity receives the answer from the server.

Notification dialog is created the following way:

 private void showServerRequestDialog(String actionLabel){
    Intent intent = new Intent(this, DlgServerRequest.class);
    intent.putExtra(SERVER_REQUEST_ACTION, actionLabel);
    startActivity(intent);

}

so when the user tries to authenticate the following method is called:

private void authenticateUser(String IMEI, String username, String password){
    mEncoderConnection.authenticateRequest(IMEI, username, password);
    showServerRequestDialog("Authenticating...");
}

and onAuthenticateResponse handles authentication response:

public void onAuthenticateResponse(AuthenticateResponse pkg) {
    //code for response handling
    //TODO: close ServerRequestDialog
    }
}

I would appreciate if anyone could suggest a way to close the notification dialog (DlgServerRequest) when the onAuthenticateUser() is executed.

Answer

CommonsWare picture CommonsWare · Sep 28, 2009

Why not use a real ProgressDialog or some other Dialog? Then, all you need to do is dismissDialog(), and you're done?

If that is unacceptable, you have two main courses of action that I can see:

  1. Move your authentication logic into the DlgServerRequest class, so it can finish() itself.
  2. Put your instance of your DlgServerRequest class into a static data member so your main activity can call finish() on it

If you choose option #2, it is really important to null out that static data member to avoid memory leaks.