首页 > 解决方案 > 没有互联网的移动通知(仅限本地网络)

问题描述

我是 xamarin 的新手,我需要从本地服务器发送和接收通知。

我的项目要求没有数据流出建筑物。我们现在有一个移动应用程序可以处理建筑物中的多种类型的事件。我们希望将通知从服务器发送到移动应用程序。

有人可以建议我阅读一些关于如何实现这一目标的文章吗?

请注意,服务器可以访问 Internet,但不能访问为业务 Web 应用程序和移动应用程序提供服务的路由器。

我发现的一切都与云有关。也许我不使用权限关键字。

谢谢!:)

编辑: 大楼有一个没有互联网的 wifi,可以为实习生网络应用程序提供服务。我们需要能够仅在此 wifi 上接收通知。由于覆盖距离,我们不能使用蓝牙。

标签: c#xamarinxamarin.formspush-notificationxamarin.android

解决方案


由于“真正的”推送通知需要向 Google Cloud Services 或 Apple Push Notification Services 注册,因此您必须使用本地通知。

这些是从您的应用程序创建的(下面的示例代码)。但是,您的网络中需要某种服务来提供通知。

我在这里看到两种可能的解决方案:

  1. 您的应用程序会定期连接到本地服务器并询问是否有任何待处理的通知,如果是,则抛出本地通知
  2. 您通过 UDP 连接发送通知,而您的应用程序侦听开放端口(这将允许您直接向设备 IP 发送通知或使用广播向所有设备发送通知)

不幸的是,我目前没有任何示例代码,但我想你应该找到很多关于如何调用 api 或如何监听套接字的示例。

但正如所承诺的,这里是从您的应用程序创建本地通知的代码。

要创建本地通知,请在您的共享代码中创建一个接口(例如 ILocalNotification.cs)

public interface ILocalNotification
{
    ShowNotification(string title, string message);
}

然后在您的本机实现中,添加以下代码:

安卓

public class LocalNotification : ILocalNotification
{
    public void ShowNotification(string title, string message)
    {
        Context act = ((Activity)MainApplication.FormsContext);
        Intent intent = new Intent(act, typeof(MainActivity));

        // Create a PendingIntent; we're only using one PendingIntent (ID = 0):
        const int pendingIntentId = 0;
        PendingIntent pendingIntent =
            PendingIntent.GetActivity(act, pendingIntentId, intent, PendingIntentFlags.OneShot);

        Notification.Builder builder = new Notification.Builder(act)
            .SetContentIntent(pendingIntent)
        .SetContentTitle(title)
        .SetContentText(message)
        .SetSmallIcon(Resource.Drawable.icon);

        Notification notification = builder.Build();
        NotificationManager notificationManager =
            act.GetSystemService(Context.NotificationService) as NotificationManager;
        const int notificationId = 0;
        notificationManager.Notify(notificationId, notification);
    }
}

iOS

public class LocalNotification : ILocalNotification
{
    public void ShowNotification(string title, string message)
    {
        UILocalNotification notification = new UILocalNotification();
        notification.AlertAction = title;
        notification.AlertBody = message;
        notification.ApplicationIconBadgeNumber = 1;
        UIApplication.SharedApplication.ScheduleLocalNotification(notification);
    }
}

然后使用 DependencyService 在您的共享代码中调用 SendNotification 方法。


推荐阅读