2

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?

user1118764
  • 9,255
  • 18
  • 61
  • 113
  • 1
    It's bad idea to display Alert Dialog in Service. You need activity context for showing that. so navigate to activity from service and display alert dialog – M D Jul 07 '16 at 07:01
  • OK, if I don't go the AlertDialog way, how about Toast, or some other form of notification? Note that the Activity that takes over the foreground app doesn't belong to me. It may have hijacked my Actitivy – user1118764 Jul 07 '16 at 07:38

3 Answers3

7

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();
            }

        });

        }
    }
Anupam Haldkar
  • 985
  • 13
  • 15
Sreehari
  • 5,621
  • 2
  • 25
  • 59
2

You can use Handler to get main looper. Try below snipt

Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable(){
@Override
public void run(){
 Toast.makeText(YourServiceName.this,"your   message",Toast.LENGHT_SHORT).show();
 }
});
Learn Pain Less
  • 2,274
  • 1
  • 17
  • 24
0

Try like this

final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                 Toast.makeText(getBaseContext(), "TEST", Toast.LENGTH_SHORT).show();

               handler.postDelayed(this, 1000);
                }
            },1000);
Jithu P.S
  • 1,843
  • 1
  • 19
  • 32