Back pressed events with system alert window

后端 未结 10 1516
南笙
南笙 2021-01-03 03:21

I need to dismiss system alert window on back pressed and home button event.I have tried with onKeyEvent but in vain. As we can\'t cap

10条回答
  •  既然无缘
    2021-01-03 03:57

    1. Show the Alert window through the Activity so you can detect it.

    Implement the code to detect easily Back Button or Home Button pressed.

    public class alertPopup extends Activity {
    
        Context context;
        final AlertDialog alertDialog;
        String TAG = "your Activity Name"
        boolean homePressed = false; // to detect the Homebutton pressed
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
         AlertDialog.Builder builder = newAlertDialog.Builder(YourActivity.this, R.style.AppCompatAlertDialogStyle);
         builder.setTitle("AlertDialog Title");
                ..........
                ....... // Build ur AlertDialog
    
         alertDialog= builder.create();
         alertDialog.show();
    
    
             //to detect Alert Dialog cancel when user touches outside the Dialog prompt
         alertDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    Log.v(TAG,"Alert Dialog cancelled when user touches outside the Dialog prompt")
                }
            });
    
        }
    
    
        @Override
        public void onBackPressed()
        {
        Log.v(TAG,"Back Button Pressed");
         super.onBackPressed();
    
         alertDialog.dismiss();   //dismiss the alertDialog
         alertPopup.this.finish();  // Destroy the current activity
    
         homePressed = false;
        }
    
        @Override
        public void onResume() {
            super.onResume();
            homePressed = true; // default: other wise onBackPressed will set it to false
        }
    
    
        @Override
        public void onPause() {
            super.onPause();
            if(homePressed) { 
    
            alertDialog.dismiss();   //dismiss the alertDialog
            alertPopup.this.finish();  // Destroy the current activity
    
            Log.v(TAG, "Home Button Pressed"); }
        }
    
    
        public void onDestroy(){
    
            super.onDestroy();
        }
    
    
    }
    

    Note:

    Add this Permission in Android Manifest to show the alert Window .

     
    

    Happy Coding :)

提交回复
热议问题