簡體   English   中英

如何讓 Toasts 僅在應用程序位於前台時才出現?

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

我有一個從Service內部調用的Toast 按照設計,無論應用程序的 state 是什么,它總是會出現。

如何讓它只在我的應用程序在前台時出現,而不是在其他應用程序在前面時出現? 也就是說,不將其移動到Activity代碼中。

mparaz,

有很多方法可以很容易地做你想做的事。 在我這樣做之前,我想談談你的問題中一個非常重要的缺陷。 應用程序不是活動,活動不是應用程序。 因此,應用程序不能位於前台或后台。 這僅限於活動。

一個簡單的例子,然后你回答。 您的服務是您的應用程序的一部分。 雖然Activity不是,但是加載了應用程序。 如果未加載您的應用程序,則您的服務無法運行。 我只強調這一點,因為它是Android中的一個重要哲學,理解這些術語的正確使用以及定義它們的概念將使您在將來更容易。

簡單的解決方案

您可以擴展Application對象並在類中保存一個簡單的公共標志。 然后,您可以在活動進入后台的任何時候將標志設置為false,當前往前景時將其設置為true(當然,反之亦然)。

擴展應用程序:

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

設置標志:在您的活動中......

//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;
}

在您的服務中(您稱之為Toast)

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

它真的很簡單。 哦是的...不要忘記告訴清單你正在擴展應用程序。 對於AndroidManifest.xml中的Application聲明

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

希望這可以幫助,

FuzzicalLogic

只需放置一些旗幟

public class MyActivity {

    private boolean isInForeground;

    protected onResume() {
        isInForeground = true;
    }

    protected onPause() {
        isInForeground = false;
    }

    private displayToast() {
        if(isInForeground) {
           Toast.makeToast().show();
        }
    }

}

我不是很擅長,但我想如果你把你的Toast放在onResume()中,它就會在你的app上運行。

很久以前就有人問過這個問題,並且已經找到了答案,但我認為我的答案使用起來更簡單。 所以我認為它會對剛接觸這項研究的人有所幫助。

ActivityManager.RunningAppProcessInfo myProcess = new ActivityManager.RunningAppProcessInfo();
ActivityManager.getMyMemoryState(myProcess);
boolean isInForeground = myProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND;

if (isInForeground) {
    showCustomMessage(LoginActivity.this, getString(R.string.activationremaining) + (iLoginReply.getResult() - 10000));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM