仅在应用程序处于后台时发送推送通知 [英] Sending a push notification only when app is in background

查看:115
本文介绍了仅在应用程序处于后台时发送推送通知的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用NotificationManager,NotificationChannel和NotificationCompat.Builder在触发事件时显示推送通知,没有在线Firebase.

I use NotificationManager, NotificationChannel and NotificationCompat.Builder to display a push notification when an event is triggered, no online Firebase.

当我的应用程序处于前台和后台时,将显示推送通知,但仅当我的应用程序处于后台时,才应该显示.

The push notification appears when my app is in foreground and background, but it only should appear when my app in the background.

我有2个活动,其中只有1个知道班级,并创建了推送通知.我可以设置一个变量来显示我的Activity是否在前台(使用onResume和onPause),但是如果我的其他Activity在后台设置了通知触发器类来启动Activity,则无法使用此方法.我需要知道整个应用程序是否处于前台,但是我没有找到解决该问题的好方法.

I have 2 Activities where just only 1 knows the class, where the push notification is created. I could just set a variable that shows if my Activity is in foreground or not (with onResume and onPause), but if my other Activity starts the Activity with the notification trigger class is set in background and therefore I can't use this method. I would need to know if the whole app is in foreground or not, but I didn't find a good solution for that problem.

那么还有一种方法可以在我的整个应用程序都在后台时显示推送通知吗?

So is there an other way to display push notifications just when my whole app is in background?

推荐答案

因此,我找到了解决此问题的合适且非常好的解决方案. 根据此答案: https://stackoverflow.com/a/42679191/6938043

So I found a proper and very good solution for this problem. According to this answer: https://stackoverflow.com/a/42679191/6938043

Application.ActivityLifecycleCallbacks

public class MainActivityChats extends AppCompatActivity implements Application.ActivityLifecycleCallbacks 
{
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getApplication().registerActivityLifecycleCallbacks(this);
    }

    public void onActivityResumed(Activity activity)
    {
        if(msg_updater != null)
        {
            msg_updater.set_app_is_active(true);
        }

    }
    public void onActivityPaused(Activity activity)
    {
        if(msg_updater != null)
        {
            msg_updater.set_app_is_active(false);
        }
    }

    public void onActivityStopped(Activity activity) {}
    public void onActivityCreated(Activity activity, Bundle bundle) {}
    public void onActivityStarted(Activity activity) {}
    public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {}
    public void onActivityDestroyed(Activity activity) {}
}

这篇关于仅在应用程序处于后台时发送推送通知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆