Did you know that you can navigate the posts by swiping left and right?
We all love the chat heads (or chat bubbles) from the popular Facebook Messenger. This provides very handy and easy access to the chat conversation screen no matter on which screen you are. Chat heads are very convenient for multitasking as a user can work and chat at the same time. That means if you are using the calculator app on your phone and if any new message arrives, you can open the conversation and replay the message without switching app. Pretty cool!!!
In this tutorial, we are going to learn how to create simple chat head and allow user to drag them across the screen. So that user can adjust the position of the floating widget in the screen.
So, let’s get started.
Step-1: Add android.permission.SYSTEM_ALERT_WINDOW permission to the AndroidManifest.xml file. This permission allows an app to create windows , shown on top of all other apps.
Step-2: Create the layout of the chat head you want to display.
Now create a service called ChatHeadService. Whenever you want to display a chat head, start the service using startService() command. In onCreate() of the service we will add the layout of the chat head at the top-left corner of the window.
To drag the chat head along with the user’s touch, we have to override OnTouchListener(). Whenever the user touches the chat head, we will record the initial x and y coordinates, and when the user moves the finger, the application will calculate the new X and Y coordinate and move the chat head.
Also, implement click listener to close the chat head by stopping the service when the user clicks on the close icon at the top-right of the chat head.
So finally your ChatService.java will look like below:
Before that, we need to check if the application has android.permission.SYSTEM_ALERT_WINDOW permission or not? For android version <= API22, this permission is granted by default. But for the android versions running API>22 ,we need to check for the permission run-time. If the permission is not available, we will open permission management screen to allow the user to grant permission using Settings.ACTION_MANAGE_OVERLAY_PERMISSION intent action. This will open below screen facilitate user to grant android.permission.SYSTEM_ALERT_WINDOW permission.
Here is the code snippet for the _MainActivity _that will display the chat head when the button is clicked by checking the _SYSTEM_ALERT_WINDOW_permission.
That’s it. Now build and run the project to see the results.
Here is the sample of how our final application should look like.
Don’t worry if you have any problems while building the project. Full source code is also available on GitHub. Go ahead, download and run it. Still, if you have any queries let me know in comments below or hit me on Twitter.