2016-08-04 62 views
2

私のアプリでは、特定の時間(アラームのようなもの)で発生した通知があり、アプリケーションからユーザーが終了した後にこの通知を削除する必要があります。これは可能ですか?通知を削除するxamarin

AlarmReceiver.cs

using Android.Content; 
using Android.App; 
using Android.Graphics; 

namespace XamarinWorkTimer.Droid 
{ 
    [BroadcastReceiver] 
    public class AlarmReceiver : BroadcastReceiver 
    { 
     NotificationManager manager; 
     public override void OnReceive(Context context, Intent intent) 
     { 

      string message = intent.GetStringExtra("message"); 
      string title = intent.GetStringExtra("title"); 

      Intent notIntent = new Intent(context, typeof(MainActivity)); 
      PendingIntent contentIntent = PendingIntent.GetActivity(context, 0, notIntent, PendingIntentFlags.CancelCurrent); 
      manager = NotificationManager.FromContext(context); 
      var style = new Notification.BigTextStyle(); 
      style.BigText(message); 

      int resourceId = Resource.Drawable.icon; 

      var wearableExtender = new Notification.WearableExtender() 
    .SetBackground(BitmapFactory.DecodeResource(context.Resources, resourceId)) 
       ; 

      //Generate a notification with just short text and small icon 
      var builder = new Notification.Builder(context) 
       .SetPriority((int)NotificationPriority.Max) 
       .SetVisibility(NotificationVisibility.Public) 
       .SetDefaults(NotificationDefaults.All) 
       .SetCategory(Notification.CategoryAlarm) 
       .SetContentIntent(contentIntent) 
       .SetSmallIcon(Resource.Drawable.icon) 
       .SetContentTitle(title) 
       .SetContentText(message) 
       .SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis()) 
       .SetAutoCancel(true); 

      var notification = builder.Build(); 
      manager.Notify(0, notification); 
     } 

    } 
} 

AndroidReminderService.csここ

using Android.Content; 
using Android.App; 
using Xamarin.Forms; 
using Android.OS; 

[assembly: Dependency(typeof(XamarinWorkTimer.Droid.AndroidReminderService))] 

namespace XamarinWorkTimer.Droid 
{ 
    public class AndroidReminderService : IReminderService 
    { 
     public void Remind(int seconds, string title, string message) 
     { 

      Intent alarmIntent = new Intent(Forms.Context, typeof(AlarmReceiver)); 
      alarmIntent.PutExtra("message", message); 
      alarmIntent.PutExtra("title", title); 

      PendingIntent pendingIntent = PendingIntent.GetBroadcast(Forms.Context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent); 
      AlarmManager alarmManager = (AlarmManager)Forms.Context.GetSystemService(Context.AlarmService); 

      alarmManager.Set(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + seconds * 1000, pendingIntent); 
     } 

    } 
} 
+0

利用pendingIntent.Cancel()についての詳細はhttps://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/。アプリが存在する場合はおそらくapp.csにあります –

答えて

2
PendingIntent pendingIntent; 


... 


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

pendingIntent.Cancel(); 
} 

チェック:ライフサイクル

関連する問題