Android Xamarin - Closed App Notification
I'd like to create notificiation in my app, which is going to be showed in 10 seconds. It works well, when application is running, but when I close the application, notification is
Solution 1:
you can try this.
protectedoverridevoidOnDestroy()
{
Notificator not = new Notificator();
not.ShowNotification(this);
base.OnDestroy();
}
Solution 2:
You should keep your service alive when you destroy your application.
- add
return StartCommandResult.Sticky;
in theOnStartCommand
method. - start the service
OnTaskRemoved
function.
Create your service with the Service
interface, the IntentService
is for Time-consuming operation.
classNotifyEvent : Service
{
[return: GeneratedEnum]
publicoverride StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
{
new Task(() => {
PendingIntent pIntent = PendingIntent.GetActivity(this, 0, intent, 0);
Notification.Builder builder = new Notification.Builder(this);
builder.SetContentTitle("hello");
builder.SetContentText("hello");
builder.SetSmallIcon(Resource.Drawable.Icon);
builder.SetPriority(1);
builder.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate);
builder.SetWhen(Java.Lang.JavaSystem.CurrentTimeMillis());
Notification notifikace = builder.Build();
NotificationManager notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
constint notificationId = 0;
notificationManager.Notify(notificationId, notifikace);
}).Start();
return StartCommandResult.Sticky;
}
publicoverride IBinder OnBind(Intent intent)
{
returnnull;
}
publicoverridevoidOnTaskRemoved(Intent rootIntent)
{
Intent restartService = new Intent(ApplicationContext, typeof(NotifyEvent));
restartService.SetPackage(PackageName);
var pendingServiceIntent = PendingIntent.GetService(ApplicationContext, 0, restartService, PendingIntentFlags.UpdateCurrent);
AlarmManager alarm = (AlarmManager)ApplicationContext.GetSystemService(Context.AlarmService);
alarm.Set(AlarmType.ElapsedRealtime, SystemClock.ElapsedRealtime() + 1000, pendingServiceIntent);
System.Console.WriteLine("service OnTaskRemoved");
base.OnTaskRemoved(rootIntent);
}
}
Post a Comment for "Android Xamarin - Closed App Notification"