C# 从服务发送通知

C# 从服务发送通知,c#,xamarin.android,visual-studio-2017,C#,Xamarin.android,Visual Studio 2017,我已经让我的信号服务工作,现在我需要在收到消息时向用户发送通知。我编写了已执行但未显示通知的通知代码。我的服务代码是: using System; using System.Collections.Generic; using System.Linq; using System.Text; using Acr.UserDialogs; using Android; using Android.App; using Android.Content; using Android.OS; using

我已经让我的信号服务工作,现在我需要在收到消息时向用户发送通知。我编写了已执行但未显示通知的通知代码。我的服务代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Acr.UserDialogs;
using Android;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Java.Util.Concurrent;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Transports;


namespace MyAndroid
{
    [Service]
    public class SignalRSrv : Service
    {
        private bool InstanceFieldsInitialized = false;
        private string username = "";
        private string firstname = "";
        private string lastname = "";
        private string company = "";
        private string department = "";
        private string section = "";

        private void InitializeInstanceFields()
        {
            mBinder = new LocalBinder(this);
        }

        private Handler mHandler; // to display any received messages
        private IBinder mBinder; // Binder given to clients
        private SignalRSingleton mInstance;
        private Notification notification = null;

        public SignalRSrv()
        {
            if (!InstanceFieldsInitialized)
            {
                InitializeInstanceFields();
                InstanceFieldsInitialized = true;
            }

        }

        public override void OnCreate()
        {
            base.OnCreate();
            mInstance = SignalRSingleton.getInstance();
            mHandler = new Handler(Looper.MainLooper);
            notification = RegisterForegroundService(); // here we set up the notification and start in foreground service
        }

        public override void OnDestroy()
        {
            base.OnDestroy();
        }


        public override IBinder OnBind(Intent intent)
        {

            //binder = new LocalBinder(this);
            User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            Bundle bundlee = intent.GetBundleExtra("TheBundle");
            MyUser = bundlee.GetParcelable("MyUser") as User;

            username = MyUser.Username;
            firstname = MyUser.Firstname;
            lastname = MyUser.Lastname;
            company = intent.GetStringExtra("theSelectedCompany");
            department = intent.GetStringExtra("theSelectedDepartment");
            section = intent.GetStringExtra("theSelectedSection");

            startSignalR(bundlee);
            return mBinder;
        }

        private void startSignalR(Bundle bundle)
        {
            mInstance.setmHubConnection(username, firstname,lastname,company,department,section);
            mInstance.setHubProxy();

            try
            {
                // Connect the client to the hup
                mInstance.mHubConnection.Start();

                mInstance.mHubProxy.On("broadcastMessage", (string platform, string message) =>
                {
                    try
                    {
                        showNotification(message, bundle, notification);

                    }
                    catch (System.Exception e)
                    {
                       var error = e.Message;
                    }

            }
            catch (System.Exception e) when (e is InterruptedException || e is ExecutionException)
            {
                //opps

                var x = 1;
                return;
            }
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {

            User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            Bundle bundlee = intent.GetBundleExtra("TheBundle");
            MyUser = bundlee.GetParcelable("MyUser") as User;

            username = MyUser.Username;
            firstname = MyUser.Firstname;
            lastname = MyUser.Lastname;
            company = intent.GetStringExtra("theSelectedCompany");
            department = intent.GetStringExtra("theSelectedDepartment");
            section = intent.GetStringExtra("theSelectedSection");

            startSignalR(bundlee);
            return StartCommandResult.Sticky;
        }
        Notification RegisterForegroundService()
        {
            var notification = new NotificationCompat.Builder(this)
                .SetContentTitle("League Alert")
                .SetContentText(Resources.GetString(Resource.String.notification_text))
                .SetSmallIcon(Resource.Drawable.alert_box)
                // Enlist this instance of the service as a foreground service
            StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification);
            return notification;
        }



        public void showNotification(string message, Bundle bundle, Notification notification)
        {
            int count = 1;
            try
            {
                Intent resultIntent = new Intent(this, typeof(Drawer));
                // Pass some values to SecondActivity:
                resultIntent.PutExtra("TheBundle", bundle);

                // Construct a back stack for cross-task navigation:
                Android.App.TaskStackBuilder stackBuilder = Android.App.TaskStackBuilder.Create(this);
                stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(Drawer)));
                stackBuilder.AddNextIntent(resultIntent);

                // Create the PendingIntent with the back stack:            
                PendingIntent resultPendingIntent =
                    stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);

                NotificationManager notificationManager =
                    (NotificationManager)GetSystemService(Context.NotificationService);
                notificationManager.Notify(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notification);

            }
            catch (System.Exception e)
            {
                var error = e.Message;
            }
        }
        private string CreateNotificationChannel()
        {
            if (Build.VERSION.SdkInt < BuildVersionCodes.O)
            {
                // Notification channels are new in API 26 (and not a part of the
                // support library). There is no need to create a notification
                // channel on older versions of Android.
                return "";
            }

            var channelName = "My Messenger";
            var channelDescription = "My Messenger Channel"; // GetString(Resource.String.channel_description);
            var channel = new NotificationChannel("0", channelName, NotificationImportance.Default)
            {
                Description = channelDescription
            };

            var notificationManager = (NotificationManager)GetSystemService(NotificationService);
            notificationManager.CreateNotificationChannel(channel);

            return channelName;
        }
    }

    public class LocalBinder : Binder
    {
        private readonly SignalRSrv outerInstance;

        public LocalBinder(SignalRSrv outerInstance)
        {
            this.outerInstance = outerInstance;
        }

        public virtual SignalRSrv Service
        {
            get
            {
                // Return this instance of SignalRSrv so clients can call public methods
                return outerInstance;
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Acr.UserDialogs;
using Android;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Runtime;
using Android.Support.V4.App;
using Android.Views;
using Android.Widget;
using Java.Lang;
using Java.Util.Concurrent;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNet.SignalR.Client.Transports;
using Android.Net;
using Android.Media;

namespace My_Android_service
{
    [Service]
    public class SignalRSrv : Service
    {
        private bool InstanceFieldsInitialized = false;
        private string username = "";
        private string firstname = "";
        private string lastname = "";
        private string companny = "";
        private string department = "";
        private string section = "";
        private int notifyid = 0;

        private void InitializeInstanceFields()
        {
            mBinder = new LocalBinder(this);
        }

        private Handler mHandler; // to display any received messages
        private IBinder mBinder; // Binder given to clients
        private SignalRSingleton mInstance;
        private Notification notification = null;

        public SignalRSrv()
        {
            if (!InstanceFieldsInitialized)
            {
                InitializeInstanceFields();
                InstanceFieldsInitialized = true;
            }

        }

        public override void OnCreate()
        {
            base.OnCreate();
            mInstance = SignalRSingleton.getInstance();
            mHandler = new Handler(Looper.MainLooper);
        }

        public override void OnDestroy()
        {
           try
            {
                base.OnDestroy();

            }
            catch (System.Exception e)
            {
                var m = e.Message;
            }
        }


        public override IBinder OnBind(Intent intent)
        {

            User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            Bundle bundlee = intent.GetBundleExtra("TheBundle");
            MyUser = bundlee.GetParcelable("MyUser") as User;

            username = MyUser.Username;
            firstname = MyUser.Firstname;
            lastname = MyUser.Lastname;
            company = intent.GetStringExtra("theSelectedCompany");
            department = intent.GetStringExtra("theSelectedDepartment");
            Section = intent.GetStringExtra("theSelectedSection");

            startSignalR(bundlee);
            return mBinder;
        }

        private void startSignalR(Bundle bundle)
        {
            mInstance.setmHubConnection(username, firstname,lastname,company,department,section);
            mInstance.setHubProxy();

            try
            {
                // Connect the client to the hub
                mInstance.mHubConnection.Start();

                // Setup the event handler for message received
                mInstance.mHubProxy.On("broadcastMessage", (string platform, string message) =>
                {
                    try
                    {
                        showNotification(message, bundle, notification);

                    }
                    catch (System.Exception e)
                    {
                       var error = e.Message;
                    }
                });

            }
            catch (System.Exception e) when (e is InterruptedException || e is ExecutionException)
            {
                // handle any errors
                var x = 1;
                return;
            }
        }

        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {

            User MyUser = new User("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
            Bundle bundlee = intent.GetBundleExtra("TheBundle");
            MyUser = bundlee.GetParcelable("MyUser") as User;

            username = MyUser.Username;
            firstname = MyUser.Firstname;
            lastname = MyUser.Lastname;
            company = intent.GetStringExtra("theSelectedCompany");
            department = intent.GetStringExtra("theSelectedDepartment");
            section = intent.GetStringExtra("theSelectedSection");

            startSignalR(bundlee);

            // Set up Notification
            Notification notify = new Notification();
            notify.Defaults = NotificationDefaults.Sound;
            notify.Defaults = NotificationDefaults.Vibrate;

            // Start Notification system, app will crash without this
            StartForeground(Constants.SERVICE_RUNNING_NOTIFICATION_ID, notify);

            return StartCommandResult.Sticky;
        }

        public void showNotification(string message, Bundle bundle, Notification notification)
        {
            try
            {
                // Activity to open when notification clicked, I'm not doing this yet.
                //Intent intent = new Intent(this, typeof(Drawer)); //Activity you want to open
                //intent.AddFlags(ActivityFlags.ClearTop);
                //intent.PutExtra("TheBundle", bundle);
                //var pendingIntent = PendingIntent.GetActivity(this, RandomGenerator(), intent, PendingIntentFlags.OneShot);

                NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                     .SetSmallIcon(Resource.Drawable.alert_box)
                     .SetContentTitle("Message Received")
                     .SetContentText(message)
                     //.SetSound(Settings.System.DefaultNotificationUri)
                     .SetVibrate(new long[] { 1000, 1000 })
                     .SetLights(Color.AliceBlue, 3000, 3000)
                     .SetAutoCancel(true);
                //.SetContentIntent(pendingIntent);


                // If this is oreo or above, we need a channel
                NotificationChannel channel = null;

                // Set sound to be used for notification
                Android.Net.Uri alarmSound = RingtoneManager.GetDefaultUri(RingtoneType.Notification);

                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    string channelId = "OML_Messenger"; //Context.GetString(Resource.String.default_notification_channel_id);
                    channel = new NotificationChannel(channelId, "Message Received", NotificationImportance.Default);
                    channel.Description = ("Message Received From Administrator");
                    notificationBuilder.SetSound(alarmSound);
                    notificationBuilder.SetChannelId(channelId);
                }

                // Connect to the notification system setup in OnStartCommandResult
                NotificationManager notificationManager = (NotificationManager)Android.App.Application.Context.GetSystemService(Context.NotificationService);

                // Create the channel, if not null
                if (!channel == null)
                {
                    notificationManager.CreateNotificationChannel(channel);
                }
                notifyid = RandomGenerator(); // Get a channel ID

                // Send the noitification
                notificationManager.Notify(notifyid, notificationBuilder.Build());

            }
            catch (System.Exception e)
            {
                var error = e.Message;
            }
        }
        private int RandomGenerator()
        {
            return new Random().Next(int.MinValue, int.MaxValue);
        }
    }

    public class LocalBinder : Binder
    {
        private readonly SignalRSrv outerInstance;

        public LocalBinder(SignalRSrv outerInstance)
        {
            this.outerInstance = outerInstance;
        }

        public virtual SignalRSrv Service
        {
            get
            {
                // Return this instance of SignalRSrv so clients can call public methods
                return outerInstance;
            }
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用Acr.UserDialogs;
使用安卓系统;
使用Android.App;
使用Android.Content;
使用Android.OS;
使用Android.Runtime;
使用Android.Support.V4.App;
使用Android.Views;
使用Android.Widget;
使用Java.Lang;
使用Java.Util.Concurrent;
使用Microsoft.AspNet.signal.Client;
使用Microsoft.AspNet.signal.Client.Transports;
名称空间MyAndroid
{
[服务]
公共类信号机RV:服务
{
private bool InstanceFieldsInitialized=false;
私有字符串用户名=”;
私有字符串firstname=“”;
私有字符串lastname=“”;
私人字符串公司=”;
私人弦部=”;
私有字符串部分=”;
私有void InitializeInstanceFields()
{
mBinder=新的LocalBinder(此);
}
私有处理程序mHandler;//显示任何接收到的消息
私有IBinder mBinder;//提供给客户端的活页夹
私人信号单分钟;
私有通知=null;
公共信号机
{
如果(!InstanceFieldsInitialized)
{
初始化instancefields();
InstanceFieldsInitialized=true;
}
}
public override void OnCreate()
{
base.OnCreate();
minInstance=signalsingleton.getInstance();
mHandler=新处理程序(Looper.MainLooper);
notification=RegisterForegroundService();//这里我们设置通知并在前台服务中启动
}
公共覆盖无效OnDestroy()
{
base.ondestory();
}
公共覆盖iBind OnBind(意图)
{
//活页夹=新的本地活页夹(此);
用户MyUser=新用户(“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,”,“,”);
Bundle bundlee=intent.GetBundleExtra(“Bundle”);
MyUser=bundlee.GetParcelable(“MyUser”)作为用户;
username=MyUser.username;
firstname=MyUser.firstname;
lastname=MyUser.lastname;
公司=intent.GetStringExtra(“所选公司”);
部门=intent.GetStringExtra(“所选部门”);
节=intent.GetStringExtra(“所选节”);
startSignalR(bundlee);
返回mBinder;
}
专用void startSignalR(捆绑包)
{
setmHubConnection(用户名、名字、姓氏、公司、部门、部门);
mInstance.setHubProxy();
尝试
{
//将客户端连接到hup
mHubConnection.Start();
minInstance.mHubProxy.On(“广播消息”,(字符串平台,字符串消息)=>
{
尝试
{
showNotification(消息、捆绑包、通知);
}
捕获(System.e例外)
{
var错误=e.消息;
}
}
捕捉(System.Exception e)当(e是InterruptedException | | e是ExecutionException)
{
//奥普斯
var x=1;
返回;
}
}
公共覆盖StartCommandResult OnStartCommand(意图、StartCommandFlags标志、int-startId)
{
用户MyUser=新用户(“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,“,”,”,“,”);
Bundle bundlee=intent.GetBundleExtra(“Bundle”);
MyUser=bundlee.GetParcelable(“MyUser”)作为用户;
username=MyUser.username;
firstname=MyUser.firstname;
lastname=MyUser.lastname;
公司=intent.GetStringExtra(“所选公司”);
部门=intent.GetStringExtra(“所选部门”);
节=intent.GetStringExtra(“所选节”);
startSignalR(bundlee);
返回StartCommandResult.Sticky;
}
通知注册表ForegroundService()
{
var notification=new NotificationCompat.Builder(此)
.SetContentTitle(“联盟警报”)
.SetContentText(Resources.GetString(Resource.String.notification_text))
.SetSmallIcon(Resource.Drawable.alert_框)
//将此服务实例登记为前台服务
StartForeground(Constants.SERVICE\u RUNNING\u NOTIFICATION\u ID,NOTIFICATION);
退货通知;
}
公共void showNotification(字符串消息、捆绑包、通知通知)
{
整数计数=1;
尝试
{
意向结果=新意向(此,类型为(抽屉));
//将一些值传递给SecondActivity:
结果:PutExtra(“束”,束);
//构建用于跨任务导航的后堆栈:
Android.App.TaskStackBuilder stackBuilder=Android.App.TaskStackBuilder.Create(此);
AddParentStack(Java.Lang.Class.FromType(typeof(Drawer)));
stackBuilder.AddNextIntent(resultIntent);
//使用后堆栈创建Pending帐篷:
悬而未决的结果悬而未决的结果=
stackBuilder.GetPendingEvent(0,PendingEventFlags.UpdateCurrent);
通知经理通知经理=
(通知