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....

Mi Selfie Stick Tripod (Bluetooth Remote) Review

Hello Readers, Today in this article, I am going to review Mi Selfie Stick Tripod (Bluetooth Remote) . I have purchased this selfie stick 4 months back. So I thought I should share my experience with this selfie stick. Before getting into details let me list down some of its features and specification. Features Tripod Detachable Bluetooth remote Light and compact Aluminum rod 360-degree rotating phone holder Specs Color: Black & White Weight: 155 grams Version: Android 4.3 or higher, iOS 5.0 or higher Bluetooth version: 3.0 Battery life: up to 50,000 clicks and charging time 1 to 2 hours Review Looks: The product looks premium and also lightweight. The best thing it can hold any smartphone easily. I have tested this with mi and oneplus5 and this works great. Tripod: It also comes with built-in tripod stand so you fix your smartphone and click pictures using Bluetooth remote. You can also use this tripod to record youtube videos etc. Quality & Weight: Overall I am impressed with...

Shut Down the Computer using notepad

Open notepad >> Write @echo off msg * I am tired. shutdown -c “So, Bye Bye dear” -s >> Save the File as AnyName.bat When you will open this file, your Computer will Shut down on its own after showing the message in it. NOTE: FOR EDUCATIONAL PURPOSE ONLY.I AM NOT RESPONSIBLE FOR IF ANYTHING GOES WRONG….