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.

Choosing the Best Motherboard

We will look at the various factors you should take into account when choosing your gaming motherboard, to ensure that you choose the best motherboard for your needs.If you think of the processor as the brain of a computer, then the motherboard could be described as the central nervous system, responsible for relaying information between all the internal components. In other words, it’s the hub of the computer, where all other components connect to. Since the motherboard is so crucial to your system, buying the best motherboard you can afford is a good investment. Select Your CPU First Before choosing your motherboard, you should have already chosen your CPU. If you haven’t already doneA motherboard will generally only support one type of processor, such as a Pentium 4 or Athlon 64. Different CPUs have connectors that vary physically from one another. So you can’t accidentally plug in the wrong processor into the wrong motherboard. Also, take note that many motherboards

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 you don’t