Search code examples
androidbroadcastreceiverandroid-alertdialogback

Avoid Alert Dialog getting closed when back button pressed?


First thing I want to say, this was done by seeing a tutorial. Here is the Custom Alert Dialog activity part I am calling from a broadcast receiver. The only problem is the back button click. Once the Alert dialog activity got started, when I press the back button it is getting closed.

 public class AlertDialogActivity extends Activity {
    @Override 
 protected void onCreate(Bundle savedInstanceState) 
 { 
    super.onCreate(savedInstanceState);
    this.setFinishOnTouchOutside(false);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
    setContentView(R.layout.activity_inmsgdialog);
 }
  @Override
public void onBackPressed()
{
    super.onBackPressed();
    Toast.makeText(getApplicationContext(), "Back Pressed", Toast.LENGTH_SHORT).show();
}
}

I have tried onBackPressed and I'm able to see the toast message but the activity is getting closed.


Solution

  • See here:

     @Override 
    public void onBackPressed() 
    { 
        super.onBackPressed(); //Remove this line 
        Toast.makeText(getApplicationContext(), "Back Pressed", Toast.LENGTH_SHORT).show();
    } 
    

    Do not call super.onBackPressed(); code if you want to disable back button for activity. So remove this line. Hope it helps.