我创建了一个依赖项以显示通知
在我的DeviceDetails_Droid.cs文件中,我设置了30秒的闹钟
本地通知功能在应用程序处于活动状态时正常工作,但当我杀掉应用程序(关闭应用程序)时,闹钟接收器没有被调用。
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);
}
在Android的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">
- 当应用程序处于运行状态时,上述代码可以完美运行。 但是,当应用程序关闭或被终止时,通知无法正常工作。