OGeek|极客世界-中国程序员成长平台

标题: ios - Xamarin.Forms - 区分后台和前台应用中心推送通知 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:00
标题: ios - Xamarin.Forms - 区分后台和前台应用中心推送通知

我们正在使用 App Center Push Notification 并根据以下文章 https://learn.microsoft.com/en-us/appcenter/sdk/push/xamarin-forms ,可以在 App.xaml.cs 中使用 Push.PushNotificationReceived 处理推送通知。

这实际上是工作的ATM,并且该方法实际上是为后台和前台通知触发的。

我们需要能够区分它们。每当用户点击通知(背景)时,我们都会将用户导航到应用的特定部分,如果应用已经打开(前景),我们就不能这样做。

我已经看到了一些实现这一点的方法,但它们都是特定于平台的(在本例中为 iOS)。有没有办法在 PCL 中做同样的事情?



Best Answer-推荐答案


我认为 Xamarin Forms 没有为我们提供获取应用程序状态的 api。

您可以通过在 Xamarin.Forms 中使用 DependencyService 来实现此目的:

首先在你的 PCL 项目中定义一个接口(interface):

public interface IGetAppState
{
    bool appIsInBackground();
}

在 iOS 中:

[assembly: Dependency(typeof(GETAppState_iOS))]

namespace App129.iOS
{
    public class GETAppState_iOS : IGetAppState
    {
        public bool appIsInBackground()
        {
            UIApplicationState state = UIApplication.SharedApplication.ApplicationState;
            bool result = (state == UIApplicationState.Background);

            return result;
        }
    }
}

在 Android 中:

[assembly: Dependency(typeof(GETAppState_Android))]

namespace App129.Droid
{
    public class GETAppState_Android : IGetAppState
    {
        public bool appIsInBackground()
        {
            bool isInBackground;

            RunningAppProcessInfo myProcess = new RunningAppProcessInfo();
            GetMyMemoryState(myProcess);
            isInBackground = myProcess.Importance != Importance.Foreground;

            return isInBackground;
        }
    }
}

在您想知道您的应用是在后台还是前台的任何地方,您都可以使用:

bool isInBackground = DependencyService.Get<IGetAppState>().appIsInBackground();

关于ios - Xamarin.Forms - 区分后台和前台应用中心推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53948023/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4