title: How to add a floating view to Android Window manager and listen to System/Hardware back button events
body: <p>I have a service which displays a floating view on the window manager (using WINDOW_TYPE_ALERT permission). I'm able to display it and perform actions. But, I have two specific questions: </p>
  
  <ol>
  <li>Regarding the implementation of the floating view</li>
  <li>How to listen to system back button event so that I can dismiss the view.</li>
  </ol>
  
  <p><strong>Implementation:</strong></p>
  
  <p>In the manifest I added permissions for:</p>
  
  <pre><code>&lt;uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /&gt;
  </code></pre>
  
  <p>I have a broadcast receiver which will listen for Alarm events. Upon receiving the event, I'm starting a service to display the floating view. The following is the code I'm using to create the view.</p>
  
  <pre><code>LayoutParams layOutParams = new WindowManager.LayoutParams(
                  WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
                  WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
                  PixelFormat.TRANSLUCENT);
  </code></pre>
  
  <p>Whenever a user performs any action on the view, I'm removing the view from window manager and killing the service.</p>
  
  <p>What I would like to know is - if this is the right way to approach the problem or are there any better ways to do it? And, should I make changes to the LayoutParams or keep them as is?</p>
  
  <p>Secondly, I would also like to dismiss this floating view when there is SYSTEM BACK/HARDWARE BACK button press event. Any pointers on how to do this would be helpful.</p>
  
  <p>Attaching a screenshot of the floating view for better understanding:</p>
  
  <p><img src="https://i.stack.imgur.com/egNte.png" alt="Floating View"></p>