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

3D ANALYZER SETTINGS

Settings for Prince of Persia Sands of Time Works with this game, u can try wid others also which are not in above list Performance section: -force zBuffer Hardware limits: -emulate HW TnL caps -emulate Pixel shader caps ANTI-DETECT MODE section: -shaders Z-buffer section: -24 bit zbuffer(with stencil) DirectX DeviceID’s section: NVIDIA GeForce Ti4600 Configuration: VendorID : 4318 Device ID :592 Works well in the following or higher configuration -Intel 865GSA motherboard, -512 MB RAM, -Pentium D dual core 2.66 GHz processor, -No graphics card required…….. have fun.

SMACKDOWN HERE COMES THE PAIN PCSX2 SETTINGS

Smack Down Here Comes The Pain Configuration: GRAPHICS-GSDX 1600(MSVC 15.00 SSSE3)0.1.15 CONTROLLERS-LILLY PAD 0.10.0 CDVDROM-EPP POLLING CDVD DRIVER 0.4.0 USB-USB NULL DRIVER 0.6.0 SOUND-SPU2-X1.1.0 SECOND CONTROLLER-LILLY PAD 0.10.0 DEV9-DEV9NULL DRIVER-0.4.0 FIRE WIRE-FWNULL DRIVER 0.5.0 BIOS-EUROPE V01.60(04/10/2001)CONSOLE SYSTEM REQUIREMENTS FOR PCSX2- MINIMUM - * Windows/Linux OS * CPU: Any that supports SSE2 (Pentium 4 and up, Athlon64 and up) * GPU: Any that supports Pixel Shader model 2.0, except Nvidia FX series (broken SM2.0, too slow anyway) * 512mb RAM (note Vista needs at least 2gb to run reliably) RECOMMENDED - * Windows Vista 32bit/64bit with the latest DirectX * CPU: Intel Core 2 Duo @ 3.2ghz or better * GPU: 8600gt or better (for Direct3D10 support) * RAM: 1gb on Linux/Windows XP, 2gb or more on Vista MY SYSTEM REQUIREMENTS WINDOWS XP SP3 PENTIUM DUAL CORE 2.6GHZ (E5300) 2GB RAM ZOTAC 8400GS 512MB DIRECT-X 9...

Choosing the Best CPU for Your Gaming Computer

Picking the latest, fastest or most expensive processor on the market won’t always result in the right CPU for your particular system. Some processors are designed to work with certain motherboards, so the CPU you choose will limit the type of motherboard you can get. The CPU (Central Processing Unit) is one of the most important components in any computer system. The CPU could be described as the brains of a computer. It contains the logic circuitry that performs the instructions of the software you run. The performance of your games and other applications will be directly related to this tiny little microprocessor. The Major Players: Intel and AMD Two companies dominate the CPU market, Intel and AMD (Advanced Micro Devices). Both companies make a range of different processor models.  For example, Intel have the Core i7 and Core i5 processor models, while AMD have the Athlon and Phenom series.  The Best CPU for Gaming If you’re a basic computer user and y...