Search code examples
androidandroid-asynctaskdialogandroid-themeactivity-finish

How to close dialog themed Activity


I have a dialog themed activity that contains only a ProgressBar with a single TextView. The code of that activity looks like this:

public class ProgressDialog extends Activity{

TextView msg;
ProgressBar progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.progress_dialog);

    msg = (TextView)findViewById(R.id.progressMsg);
    progressBar = (ProgressBar)findViewById(R.id.progressBar);
    Intent intent = getIntent();
    String msgString = intent.getStringExtra("msg");
    msg.setText(msgString);

}

}

This represents a ProgressBar Dialog that I will use for my Project so that I have a same look and easy costumizable Dialog on all versions of Android.

The problem is how can I finish this activity from an AsyncTask onPostExecute() method if I start it in the onPreExecute() method as a normal activity. The AsyncTask is called in another Activity. I tried different things but have not managed to succeed. I tried:

  • Simulate a back press button
  • Using fragmentManager and activityManager
  • Implementing a public method in the Activity that calls the finish() method for an activity

Please help! If you need some additional code let me know!

Best regards!


Solution

  • Write a method along these lines in the calling activity and call it to remove the dialog:

    private void removeDialog() {
        Intent removeDialogIntent = new Intent(this, ProgressDialogActivity.class).setAction(ACTION_CLOSE_DIALOG);
        startActivity(removeDialogIntent);
    }
    

    And in the progressDialogActivity make sure to handle it:

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    
        if (ACTION_CLOSE_DIALOG.equals(intent.getAction())){
            finish();
        }
    }
    

    You can stop the activity from a service or any other context, just add the relevant flags to the intent.

    Having said that, personally I would use DialogFramgent and avoid all this mess, why do you need a dialog activity...?