Search code examples
androidandroid-serviceandroid-notificationsandroid-alertdialogtoast

Showing a Toast notification from a service


I have a background service that monitors foreground apps. It's used to protect a certain app such that if the protected app is in the foreground and then pushed to the background because another app started, it would show the user a notification that another app has taken over as the foreground app.

I'm able to detect the switch, but is there any way to display a Toast notification/AlertDialog to alert the user in the service after detection?


Solution

  • You can get the app base context in Service class and show a toast using a Handler.

    private Context appContext;
    
    @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            appContext = getBaseContext();        //Get the context here
        }
    
        //Use this method to show toast
        void showToast(){
            if(null != appContext){
            Handler handler = new Handler(Looper.getMainLooper());
            handler.post(new Runnable() {
                @Override
                public void run() 
                {
                   Toast.makeText(appContext, "Printing Toast Message", Toast.LENGTH_SHORT).show();
                }
    
            });
    
            }
        }