Quantcast
Channel: Recent Threads — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 204402

Schedule notification using alarm manager in xamarin forms for android

$
0
0

I have created a dependencie to show the notifications

In My DeviceDetails_Droid.cs I've set set alarm for 30 seconds

public void ShowNotification(string message, string title)
{
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);

    //TODO: For demo set after 5 seconds.
    alarmManager.Set(AlarmType.RtcWakeup, DateTime.Now.Millisecond + 30000, pendingIntent);

}

In Androids MainActivity
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive (Context context, Intent intent)
{

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

        var notIntent = new Intent (context, typeof(MainActivity));
        var contentIntent = PendingIntent.GetActivity (context, 0, notIntent, PendingIntentFlags.CancelCurrent);
        var manager = NotificationManagerCompat.From (context);

        var style = new NotificationCompat.BigTextStyle();
        style.BigText(message);



        //Generate a notification with just short text and small icon
        var builder = new NotificationCompat.Builder (context)
            .SetContentIntent (contentIntent)
            .SetSmallIcon (Resource.Drawable.Icon)
            .SetContentTitle (title)
            .SetContentText (message)
            .SetStyle (style)
            .SetWhen (Java.Lang.JavaSystem.CurrentTimeMillis ())
            .SetAutoCancel (true);

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

And in manifest file












<receiver android:name=".AlarmReceiver" android:enabled="true" android:exported="true" android:process=":remote" android:label="AlarmReceiver">

The above code is runs perfectly when app is in running state
But the notification is not working when app is closed or killed


Viewing all articles
Browse latest Browse all 204402

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>