How can Toasts be made to appear only if the app is in the foreground?

后端 未结 3 774
庸人自扰
庸人自扰 2021-02-09 07:17

I have a Toast that is called from inside a Service. It always appears regardless of the state of the app, as designed.

How can make it appear

相关标签:
3条回答
  • 2021-02-09 07:28

    i'm not so good in it, but i think if you place your Toast in onResume() , it run just on your app.

    0 讨论(0)
  • 2021-02-09 07:33

    mparaz,

    There are a number of ways to do what you want very easily. Before I do that, I'd like to address a very important flaw in your question. An App is not an Activity, and an Activity is not an App. As such, an app cannot be in the foreground or background. That is reserved only for Activities.

    A quick example and then to you answer. Your Service is part of your Application. The application is loaded though the Activity is not. If your Application were not loaded, your Service could not run. I only emphasize this because it is an important philosophy in Android and understanding the correct use of these terms and the concepts that define them will make it so much easier for you in the future.

    A Simple Solution

    You may extend the Application object and hold a simple public flag in the class. Then you can set the flag to false anytime the activity goes to the background and true when it comes to the foreground (or vice versa, of course).

    Extending the Application:

    public class MyApplication extends Application
    {
        static public boolean uiInForeground = false;
    }
    

    Setting the flag: In your Activity...

    //This may be done in onStart(), onResume(), onCreate()... 
    //... whereever you decide it is important. 
    //Note: The functions here do not include parameters (that's Eclipse's job).
    public void onStart()
    {//Notice the static call (no instance needed)
        MyApplication.uiInForeground = true;
    }
    
    public void onPause()
    {
        MyApplication.uiInForeground = false;
    }
    

    In your Service (where you call the Toast)

        if (MyApplication.uiInForeground)
            Toast.makeText(someContext, myMsg).show();
    

    It's really as simple as that. Oh yeah... Don't forget to tell the manifest that you are extending the Application. For your Application declaration in AndroidManifest.xml

    <application android:name=".MyApplication" .... >
       <!-- All other components -->
    </application>
    

    Hope this helps,

    FuzzicalLogic

    0 讨论(0)
  • 2021-02-09 07:51

    Just place some flag

    public class MyActivity {
    
        private boolean isInForeground;
    
        protected onResume() {
            isInForeground = true;
        }
    
        protected onPause() {
            isInForeground = false;
        }
    
        private displayToast() {
            if(isInForeground) {
               Toast.makeToast().show();
            }
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题