2016-06-19 2 views
0

Я ищу, чтобы создать текстовую игру на Android, используя C# в Xamarin Forms.Pushing уведомления, когда приложение закрыто

В рассказе я хочу задать задачи персонажа, на которые потребуется некоторое время, например. «Я буду копать эту дыру, я дам вам жужжание, когда закончите».

Как настроить уведомления, появляющиеся после установленного времени? Например, вышеуказанный оператор может занять 10 минут, а затем пользователь получает уведомление для продолжения игры?

Я только начал C# неделю назад, поэтому прошу прощения, если это noobish или уже спрошено. Я смотрел повсюду, но есть несколько типов уведомлений, и кажется, что я читаю французский, когда я пытаюсь понять это.

ответ

0

Я хотел бы начать с создания 2 интерфейсов в проекте PCL:

public interface IAlarm { 
    void SetAlarm(); 
} 

public interface INotification { 
    void Notify(LocalNotification notification); 
} 

Затем в проекте Android, создать реализации:

сигнализации Помощник

[assembly: Dependency(typeof(AlarmHelper))] 
namespace Test.Droid 
{ 
    class AlarmHelper: IAlarm 
    { 
     public void SetAlarm(int minutes) 
     { 
      var alarmTime = Calendar.Instance; 
      alarmTime.Add(CalendarField.Minute, minutes); 

      var intent = new Intent(Android.App.Application.Context, typeof(ScheduledAlarmHandler)); 
      var pendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, intent, PendingIntentFlags.CancelCurrent); 
      var alarmManager = Android.App.Application.Context.GetSystemService(Context.AlarmService) as AlarmManager; 

      alarmManager.Set(AlarmType.RtcWakeup, alarmTime.TimeInMillis, pendingIntent); 
     } 
    } 
} 

Помощник по уведомлению

[assembly: Dependency(typeof(NotificationHelper))] 
namespace Test.Droid 
{ 
    class NotificationHelper : INotification 
    { 
     public void Notify (string title, string text) 
     {    
      NotificationManager notificationManager = (NotificationManager) Android.App.Application.Context.GetSystemService(Context.NotificationService); 

      Intent intent = new Intent(Android.App.Application.Context, typeof(MainActivity)); 
      PendingIntent pIntent = PendingIntent.GetActivity(Android.App.Application.Context, 0, intent, PendingIntentFlags.OneShot); 

      Notification nativeNotification = new Notification(); 

      var builder = new NotificationCompat.Builder(Android.App.Application.Context) 
      .SetContentTitle(title) 
      .SetContentText(text) 
      .SetSmallIcon(Resource.Drawable.ic_notif) // 24x24 dp 
      .SetLargeIcon(BitmapFactory.DecodeResource(Android.App.Application.Context.Resources, Android.App.Application.Context.ApplicationInfo.Icon)) 
      .SetPriority((int)NotificationPriority.Default) 
      .SetAutoCancel(true) 
      .SetContentIntent(pIntent); 

      notificationManager.Notify(0, builder.Build()); // Id 0 can be random 
     } 
    } 
} 

Когда время ожидания закончится, BroadCastReceiver будет называться:

[BroadcastReceiver] 
class ScheduledAlarmHandler : WakefulBroadcastReceiver 
{ 
    public override void OnReceive(Context context, Intent intent) 
    { 
     // Implement quick checking logic here if notification is still required, plus its tittle and text 
     // you have 10 seconds max in this method and cannot use 'await' 

     var notificationHelper = new NotificationHelper(); 
     notificationHelper.Notify("Title","Text"); 
    } 
} 

В игровой проект PCL логики, вы можете установить новый сигнал следующим образом:

alarmHelper = DependencyService.Get<IAlarm>(); 
alarmSetter.SetAlarm(10); // 10 minutes from now 

I намеренно отделили логику уведомлений Alarm &, чтобы вы могли проверить через 10 минут, если уведомление все еще должно отображаться и установить его заголовок и текст. Альтернативой является передача заголовка и текста во время установки сигнала тревоги с помощью intent.putextra.

Смежные вопросы