How to Draw Over Other Apps in Android?
Sometimes we require our app to show some content on the main screen irrespective of the app running in the foreground, this process is known as drawing over other apps. There are many apps that use this functionality to provide maximum features with minimum screen coverage. This also enables the user to do multitasking. For example, the chat bubble of Facebook Messenger, Mobile Over Usage notice of YourHour App, Voice Command of Google, and many more. We can create similar functionality using the WindowManager interface provided by Android SDK.
The Android WindowManager is a system service that controls which windows are displayed and how they are arranged on the screen. When you launch or close an app or rotate the screen, it automatically executes window transitions and animations, among other things.
Every activity has its own Window that displays its content on the screen. When you execute setContentView on an activity, it adds the view to the default window of the activity. Because the default window fills the screen and hides any other activities, the WindowManager will show whatever window is on top. So, in most cases, you don’t need to bother about windows; simply build activity, and Android will take care of the rest. In order to manipulate the Window, we need to interact with the window manager. Now in order to display over other apps, we need to create some kind of service, because the activity will close when some other app comes into the foreground.
What we are going to build in this article?
A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the AndroidManifest.xml file
In order to draw over other apps we require, android.permission.SYSTEM_ALERT_WINDOW permissions and for android with API version > 23 we need to ask for this on runtime. android.permission.SYSTEM_ALERT_WINDOW allows an app to create windows using the type WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, shown on top of all other apps.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 4: Creating the popup_window.xml layout file
Step 5: Working with Window.java
Step 6: Creating the ForegroundService class
Step 7: Working with MainActivity.java
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.