如何敬酒进行到出现只有当应用程序是在前台?是在、前台、应用程序

2023-09-05 08:58:42 作者:你曾路过我的心

我有一个吐司是从服务内部调用。 它总是会出现,无论应用程序的状态,作为设计的。

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

怎样才能使它只在我的应用程序是在前台出现,而不是在其他应用程序在前面?也就是说,如果没有它移动到活动 code。

How can make it appear only when my app is in the foreground, and not when other apps are in front? That is, without moving it to Activity code.

推荐答案

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.

一个简单的例子,然后给你回答。你的服务是应用程序的一部分。该应用程序加载,虽然该活动并非如此。如果没有加载您的应用程序,您的服务无法运行。我只强调这一点,因为它是Android的一个重要理念,了解正确的使用这些术语和定义的概念,他们将使它这么多,你更容易的未来。

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.

一个简单的解决方案

您可以扩展应用程序对象,并举行简单的公共标志类。然后,你可以设置为false,随时活动去的背景和真实的标志,当涉及(当然,反之亦然)到前台。

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

扩展应用:

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

这真的就这么简单。噢......别忘了告诉你的扩展应用程序的清单。对于在AndroidManifest.xml中的应用程序声明

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

FuzzicalLogic