user1118764 user1118764 - 7 months ago 56
Android Question

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?


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

private Context appContext;

    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()); Runnable() {
            public void run() 
                    Toast.makeText(appContext, "Toast Message", Toast.LENGTH_SHORT)show();