Back pressed events with system warning window

I need to cancel the system warning window while backpressed and the homeevent.I button tried with onKeyEvent, but in vain. Since we cannot capture the clicked event backin the service, how to do this?

+5
source share
9 answers

Since this is the service that hosts the overlay window, this is a bit complicated solution, but it is possible.

You must handle these two cases separately (redefinition of pressing the "home" button and the "Back" button).


1. Pressing the "Home" button:

HomeWatcher, BroadcastReceiver, . , .

Android:

onCreate :

HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
    @Override
    public void onHomePressed() {
        yourWindow.hide()  //means: windowManager.removeView(view);
    }
    @Override
    public void onHomeLongPressed() {
    }
});
mHomeWatcher.startWatch();

2. "" :

, ( XML-).

, :

public class MyWindow
{
    private WindowManager windowManager;
    private WindowManager.LayoutParams params;
    private View view;

    // Add this empty layout:
    private MyLayout myLayout;

    public MyWindow()
    {
        windowManager = (WindowManager) context.getSystemService(context.WINDOW_SERVICE);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.your_original_window_layout, null);

        // Add your original view to the new empty layout:
        myLayout = new MyLayout(this);
        myLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    // And show this layout instead of your original view:
    public void show()
    {
        windowManager.addView(myLayout, params);
    }

    public void hide()
    {
        windowManager.removeView(myLayout);
    }
}

MyLayout "" :

public class MyLayout extends LinearLayout
{
    private MyWindow myWindow;

    public MyLayout(MyWindow myWindow)
    {
        super(myWindow.context);

        this.myWindow = myWindow;
    }


    @Override public boolean dispatchKeyEvent(KeyEvent event)
    {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
        {
            if (event.getAction() == KeyEvent.ACTION_DOWN  &&  event.getRepeatCount() == 0)
            {
                getKeyDispatcherState().startTracking(event, this);
                return true;

            }

            else if (event.getAction() == KeyEvent.ACTION_UP)
            {
                getKeyDispatcherState().handleUpEvent(event);

                if (event.isTracking() && !event.isCanceled())
                {
                    // dismiss your window:
                    myWindow.hide();

                    return true;
                }
            }
        }

        return super.dispatchKeyEvent(event);
    }
}

, , , , , . , . .

+5

.

  public void onBackPressed()
  {
        super.onBackPressed();
  }
+1

onBackPressed.

@Override
public void onBackPressed() {

    super.onBackPressed(); // remove this if u want to handle this event
}
+1

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        exitByBackKey();

        //moveTaskToBack(false);

        return true;
    }
    return super.onKeyDown(keyCode, event);
    }

    protected void exitByBackKey() {

    AlertDialog alertbox = new AlertDialog.Builder(this)
    .setMessage("Do you want to exit application?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {

            finish();
            //close();


        }
    })
    .setNegativeButton("No", new DialogInterface.OnClickListener() {

        // do something when the button is clicked
        public void onClick(DialogInterface arg0, int arg1) {
                       }
    })
      .show();

    }
0
@Override
public void onBackPressed()
{
       super.onBackPressed();
}

. super.OnBackPressed android. .

, .

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder1.setMessage("TEST DIALOG.\n");
    builder1.setPositiveButton("Ok",
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                Toast.makeText(MainActivity.this, "This Is test Dialog", Toast.LENGTH_SHORT).show();
        }
    });
    AlertDialog alert11 = builder1.create();
    alert11.show();

.

, !

0

dispatchKeyEvent, :

public class CustomSystemAlertWindow extends FrameLayout {

    public static final String TAG = "CustomSystemAlertWindow";

    private WeakReference<Context> mContext;

    public CustomSystemAlertWindow(Context context) {
        super(context);

        mContext = new WeakReference<Context>(context);

        // Set a background color to identify the view on the screen
        this.setBackgroundColor(getResources().getColor(android.R.color.holo_red_light));
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event != null && event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            Log.d(TAG, "back button pressed");

            if (mContext != null && mContext.get() != null) {
                WindowManager wm = (WindowManager) mContext.get().getSystemService(Context.WINDOW_SERVICE);
                wm.removeView(this);
            }

            return true;
        }

        return super.dispatchKeyEvent(event);
    }
}

:

CustomSystemAlertWindow customSystemAlertWindow = new CustomSystemAlertWindow(context);

WindowManager.LayoutParams params = new WindowManager.LayoutParams(
        WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.MATCH_PARENT,
        WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
        WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
        PixelFormat.TRANSLUCENT);

WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
wm.addView(customSystemAlertWindow, params);

"", .

0
  • "" "", .

Back Button Home.

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();
    }


}

:

Android Manifest, .

 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

:)

0

, <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> .

, back, home ( ).

back, , . :

    // Wrapper for intercepting System/Hardware key events
    ViewGroup wrapper = new FrameLayout(this) {
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
                hideAddNotesFloatingView();
                return true;
            }
            return super.dispatchKeyEvent(event);
        }
    };

:

        mAddNoteFloatingView = mInflater.inflate(R.layout.floating_add_note, wrapper);

:

private void addFloatingView() {
    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.MATCH_PARENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            0,
            PixelFormat.TRANSLUCENT);

    params.gravity = Gravity.CENTER | Gravity.LEFT;
    params.x = 0;
    params.y = 0;

    // Wrapper for intercepting System/Hardware key events
    FrameLayout wrapper = new FrameLayout(this) {
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode()==KeyEvent.KEYCODE_BACK) {
                // Add your code for handling the back button press
                return true; // Return true means that the event was handled
            }
            return super.dispatchKeyEvent(event);
        }
    };

    mAddNoteFloatingView = mInflater.inflate(R.layout.floating_view, wrapper);

    mWindowManager.addView(mAddNoteFloatingView, params);
}
0

. :

  • Relative Layout, Linear Layout Frame Layout . 2. dispatchKeyEvent.
  • addView().
  • Window Manager Alert Dialog , .
0

Source: https://habr.com/ru/post/1015772/


All Articles