首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么NotificationManager notificationManager = (NotificationManager)GetSystemService(LocalNotificationService);显示错误?

为什么NotificationManager notificationManager = (NotificationManager)GetSystemService(LocalNotificationService);显示错误?
EN

Stack Overflow用户
提问于 2019-05-04 01:56:58
回答 1查看 1.5K关注 0票数 1

我正在编写本地通知,并且正在创建LocalNotificationService,当我想要创建NotificationManager时,它会在该行显示错误:

代码语言:javascript
运行
复制
NotificationManager notificationManager =(NotificationManager)GetSystemService(LocalNotificationService);

请帮帮我!谢谢!完整代码:

组件: Xamarin.Forms.Dependency(typeof(LocalNotificationService))

命名空间Tyron.DependencyServices.Droid{

代码语言:javascript
运行
复制
public class LocalNotificationService : ILocalNotificationService       
{       
    int _notificationIconId { get; set; }       
    readonly DateTime _jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);       
    internal string _randomNumber;
    public const string URGENT_CHANNEL = "main";
    public void LocalNotification(string title, string body, int id, DateTime notifyTime){       

        //long repeateDay = 1000 * 60 * 60 * 24;       
        long repeateForMinute = 86400000; // In milliseconds      
        long totalMilliSeconds = (long)(notifyTime.ToUniversalTime() - _jan1st1970).TotalMilliseconds;       
        if (totalMilliSeconds < JavaSystem.CurrentTimeMillis()){       
            totalMilliSeconds = totalMilliSeconds + repeateForMinute;       
        }



        string chanName = "mainChanel";
        var importance = NotificationImportance.High;
        NotificationChannel chan = new NotificationChannel(URGENT_CHANNEL, chanName, importance);
        chan.EnableVibration(true);
        chan.LockscreenVisibility = NotificationVisibility.Public;
        NotificationManager notificationManager = (NotificationManager)GetSystemService(LocalNotificationService); // shows error: GetSystemService is not allowed at this context
        notificationManager.CreateNotificationChannel(chan);
        var intent = CreateIntent(id);       
        var localNotification = new LocalNotification();       
        localNotification.Title = title;       
        localNotification.Body = body;       
        localNotification.Id = id;       
        localNotification.NotifyTime = notifyTime;       

        if (_notificationIconId != 0){       
            localNotification.IconId = _notificationIconId;       
        }       
        else{       
            localNotification.IconId = Resource.Drawable.ic_mr_button_connecting_30_light;       
        }       

        var serializedNotification = SerializeNotification(localNotification);       
        intent.PutExtra(ScheduledAlarmHandler.LocalNotificationKey, serializedNotification);       

        Random generator = new Random();         
        _randomNumber = generator.Next(100000, 999999).ToString("D6");        

        var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);       
        var alarmManager = GetAlarmManager();       
        alarmManager.SetRepeating(AlarmType.RtcWakeup, totalMilliSeconds, repeateForMinute, pendingIntent);       
    }










    public void Cancel(int id){       

        var intent = CreateIntent(id);       
        var pendingIntent = PendingIntent.GetBroadcast(Application.Context, Convert.ToInt32(_randomNumber), intent, PendingIntentFlags.Immutable);       
        var alarmManager = GetAlarmManager();       
        alarmManager.Cancel(pendingIntent);       
        var notificationManager = NotificationManagerCompat.From(Application.Context);       
        notificationManager.CancelAll();       
        notificationManager.Cancel(id);       
    }       

    public static Intent GetLauncherActivity(){       

        var packageName = Application.Context.PackageName;       
        return Application.Context.PackageManager.GetLaunchIntentForPackage(packageName);       
    }       


    private Intent CreateIntent(int id){       

        return new Intent(Application.Context, typeof(ScheduledAlarmHandler))       
            .SetAction("LocalNotifierIntent" + id);       
    }       

    private AlarmManager GetAlarmManager(){       

        var alarmManager = Application.Context.GetSystemService(Context.AlarmService) as AlarmManager;       
        return alarmManager;       
    }       

    private string SerializeNotification(LocalNotification notification){       

        var xmlSerializer = new XmlSerializer(notification.GetType());       

        using (var stringWriter = new StringWriter()){       
            xmlSerializer.Serialize(stringWriter, notification);       
            return stringWriter.ToString();       
        }       
    }       
}       

[BroadcastReceiver(Enabled = true, Label = "Local Notifications Broadcast Receiver")]       
public class ScheduledAlarmHandler : BroadcastReceiver{       

    public const string LocalNotificationKey = "LocalNotification";       

    public override void OnReceive(Context context, Intent intent){       
        var extra = intent.GetStringExtra(LocalNotificationKey);       
        var notification = DeserializeNotification(extra);       
        //Generating notification       
        var builder = new NotificationCompat.Builder(Application.Context)       
            .SetContentTitle(notification.Title) 
            .SetChannelId("main")
            .SetContentText(notification.Body)       
            .SetSmallIcon(notification.IconId)       
            .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Alarm))       
            .SetAutoCancel(true);       

        var resultIntent = LocalNotificationService.GetLauncherActivity();       
        resultIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);       
        var stackBuilder = Android.Support.V4.App.TaskStackBuilder.Create(Application.Context);       
        stackBuilder.AddNextIntent(resultIntent);       

        Random random = new Random();       
        int randomNumber = random.Next(9999 - 1000) + 1000;        

        var resultPendingIntent =       
            stackBuilder.GetPendingIntent(randomNumber, (int)PendingIntentFlags.Immutable);       
        builder.SetContentIntent(resultPendingIntent);       
        // Sending notification       
        var notificationManager = NotificationManagerCompat.From(Application.Context);       
        notificationManager.Notify(randomNumber, builder.Build());       
    }       

    private LocalNotification DeserializeNotification(string notificationString){       

        var xmlSerializer = new XmlSerializer(typeof(LocalNotification));       
        using (var stringReader = new StringReader(notificationString))       
        {       
            var notification = (LocalNotification)xmlSerializer.Deserialize(stringReader);       
            return notification;       
        }       
    }



  /*  private void createNotificationChannel()
    {
        var channelName = "main";
        var channelDescription = "The main channel";

        // set the vibration patterm for the channel
        long[] vibrationPattern = { 100, 200, 300, 400, 500, 400, 300, 200, 400 };

        // Creating an Audio Attribute
        var alarmAttributes = new AudioAttributes.Builder()
                               .SetContentType(AudioContentType.Sonification)
                               .SetUsage(AudioUsageKind.Alarm)
                               .Build();

        // Create the uri for the alarm file
        // Note: Make sure you add the mp3 file in your Android project under Resources/raw/soundFile.mp3 and set the build as Android Resource
        var alarmUri = Android.Net.Uri.Parse("MyApp.Android/Resources/raw/alarm.mp3");


        // create chan1  which is the urgent notifications channel
        var chan1 = new NotificationChannel(channelName, channelName, NotificationImportance.High)
        {
            Description = channelDescription
        };


        // set the channel properties
        chan1.EnableLights(true);
        chan1.LightColor = Color.Red;
        chan1.EnableVibration(true);
        chan1.SetVibrationPattern(vibrationPattern);
        chan1.SetSound(alarmUri, alarmAttributes);          // this is where the sound is set for the channel
        chan1.SetBypassDnd(true);
        chan1.LockscreenVisibility = NotificationVisibility.Public;

        // finally create the channel
        var manager = (NotificationManager)GetSystemService(NotificationService);

    }
    */
}

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-04 02:00:55

可以通过Context获得GetSystemService。在这种情况下,您可以使用应用程序或基于活动的应用程序。

代码语言:javascript
运行
复制
NotificationManager notificationManager = (NotificationManager)Android.App.Application.Context.GetSystemService(Android.Content.Context.NotificationService);

回复:Context

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55974967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档