Skip to main content

Android - Show A Dialog From Service

In this article, I will be discussing how you can create a dialog from service. As we all know that service in android does not have any UI and it is intended for long-running background tasks.

But sometimes it is required to show some information to the user when your app is running in the background.

Today I will show you how you can implement this type of functionality in your application.

Before starting the tutorial let me tell you about the special permission that we are going to use.

Permission

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

This permission allows the app to use the system level window.


AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.app.dialogfromservice">    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:roundIcon="@mipmap/ic_launcher_round"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".BackgroundDialogService"                       />    </application></manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context=".MainActivity">    <Button        android:id="@+id/start_service"        android:background="#009688"        android:textColor="#FFF"        android:text="Start Service"        android:textStyle="bold"        android:layout_marginEnd="16dp"        android:layout_marginStart="16dp"        android:layout_gravity="center"        android:layout_width="match_parent"        android:layout_height="wrap_content"/></LinearLayout>

MainActivity.java

package com.app.dialogfromservice;import androidx.appcompat.app.AppCompatActivity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;public class MainActivity extends AppCompatActivity implements View.OnClickListener {    private Button start_service;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        start_service = findViewById(R.id.start_service);        start_service.setOnClickListener(this);    }    @Override    public void onClick(View v) {        Intent intent = new Intent(getBaseContext(), BackgroundDialogService.class);        startService(intent);    }}

BackgroundDialogService.java

package com.app.dialogfromservice;import android.app.AlertDialog;import android.app.Service;import android.content.DialogInterface;import android.content.Intent;import android.os.Build;import android.os.Handler;import android.os.IBinder;import android.util.Log;import android.view.WindowManager;import androidx.annotation.Nullable;public class BackgroundDialogService extends Service {    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }    @Override    public void onCreate() {        super.onCreate();        Log.d("Service Message", "Service Created");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.d("Service Message", "Service Started");        Handler handler = new Handler();        handler.postDelayed(new Runnable() {            @Override            public void run() {AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());builder.setTitle("Hello").setMessage("This dialog is created from service.").setCancelable(false).setPositiveButton("Ok", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {                        dialog.cancel();                    }                });                int layout_params;                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)                {                    layout_params = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;                }                else {                    layout_params = WindowManager.LayoutParams.TYPE_PHONE;                }                final AlertDialog alert = builder.create();                alert.getWindow().setType(layout_params);                alert.show();            }        }, 10000);        return START_STICKY;    }    @Override    public void onDestroy() {        super.onDestroy();        Log.d("Service Message", "Service Destroyed");    }}

In the above class, we have a method named onStartCommand where I have written a code for showing a dialog from service. So let’s understand this in detail.

Android App Screenshot

The user interface looks very simple. So when you click on this button START SERVICE . It will start the service.

I am using the Handler class method onPostDelayed to show a dialog after 10 seconds. There are a few things which are required to understand

   int layout_params;                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)                {                    layout_params =                     WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;                }                else {                    layout_params = WindowManager.LayoutParams.TYPE_PHONE;                }

The above code checks the android os version and based on that, I am setting the window type. To show a dialog from service you need to set the window type.

So it seems work is almost completed and when you run the application and press the START SERVICE button you will see your app will crash in Oreo devices but why !!! you have done everything correct but still the app is crashing.

If you will check the Logcat you will see an exception

Unable to add window android.view.ViewRootImpl-
permission denied for window type 2038

The reason for this exception because from android API Level 26 you have to enable Display over other apps permission.

How to enable this permission

To do this you have two ways either you can check programmatically whether permission is given or either go directly to app info and enable the permission for Display over other apps. For this example I am going to manually enable the permission

Android App info image
Tap on Display over other apps
Android App info image
Now Tap on Allow display over the apps
Android App info image

Now Go back to your app and tap on the START SERVICE button and move your app in background. You will see the dialog after 10 seconds

Source code

https://github.com/vaibhavsharma316/TechieVaibhavTutorials/tree/master/DialogFromService

Also don’t forget to subscribe to get the latest updates

Thanks for reading 🙂 🙂

Comments

Popular posts from this blog

Automation - Update Naukri Profile Using Selenium

Recently one of my friend came to me with a problem. He is looking out for new job but he feels quite boring to update  his profile on daily basis. As some people says updating profile in the morning gives you more calls as it keeps the newly updated profile on top (Although i don’t know whether naukri works this way or not 😀 ). As i was more interested to solve his problem.  After listening his problem i came to solution that instead of updating it manually lets make this job automatic. And it is quite interesting how we can automate our daily boring task with automation. Another day i came with the solution . And the solution was to make it automatic using selenium (Those who are not aware about selenium do check this link) In short, Selenium is a Testing automation Framework. And it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should) also be automated as well....

OpenCV - Image Filters

Hello Guys, In this tutorial, I will discuss the color map in OpenCV. Color Map is used to show different color temperatures. And this can also be used to generate some cool image filters.  OpenCV comes with thirteen built-in color maps. So in this tutorial, I will show you how to use color maps.  Let’s get started List of Color Maps COLORMAP_AUTUMN COLORMAP_BONE COLORMAP_JET COLORMAP_WINTER COLORMAP_RAINBOW COLORMAP_OCEAN COLORMAP_SUMMER COLORMAP_SPRING COLORMAP_COOL COLORMAP_HSV COLORMAP_PINK COLORMAP_HOT COLORMAP_PARULA To apply color map first we need to convert an image to grayscale. So I will use  img = cv.imread("nature.jpg",cv.IMREAD_GRAYSCALE) If you are not aware of this function then please check my previous tutorial  http://techievaibhav.in/2019/01/10/reading-an-image-using-opencv/ To apply color maps, OpenCV comes with a function called applyColorMap() . This function takes two parameters. Gray Scale image Color Map Autumn Bone Cool Hot HSV Jet Ocean Parula Pink ...

Windows Run Commands List

Accessibility Controls – access.cpl Add Hardware Wizard – hdwwiz.cpl Add/Remove Programs – appwiz.cpl Administrative Tools control – admintools Automatic Updates – wuaucpl.cpl Bluetooth Transfer Wizard – fsquirt Calculator – calc Certificate Manager – certmgr.msc Character Map – charmap Check Disk Utility – chkdsk Clipboard Viewer – clipbrd Command Prompt – cmd Component Services – dcomcnfg Computer Management – compmgmt.msc Device Manager – devmgmt.msc Direct X Control Panel (If Installed)  – directx.cpl Direct X Troubleshooter – dxdiag Disk Cleanup Utility – cleanmgr Disk Defragment – dfrg.msc Disk Management – diskmgmt.msc Disk Partition Manager – diskpart Display Properties – control desktop Display Properties – desk.cpl Display Properties (w/Appearance Tab Preselected) – control color Dr. Watson System Troubleshooting Utility – drwtsn...