【发布时间】:2017-08-06 13:02:01
【问题描述】:
使用 Xamarin.Android。
我有一个广播接收器:
public class MyBroadcastReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
try
{
string someExtra = intent.Extras.GetString("someExtra", string.Empty);
}
catch (Exception)
{
}
}
}
我使用谷歌云消息服务并在收到消息时创建通知。使用通知构建器的 SetContentIntent,我将一些额外内容导出到活动中,如果用户打开它,该活动将运行此通知。它有效。但是,当我在 GCM 服务中使用 SetDeleteIntent 初始化通知生成器时,如果用户滑动以关闭通知,则通知不会触发 BroadcastReceiver 中的 OnReceive。
当我在我的活动中(而不是在 GCM 服务中)执行所有相同操作时,每个通知的滑动关闭事件都会触发 OnReceive。但它在服务内部不起作用。
我什至在我的活动中实现了与服务中相同的 CreateNotification 方法。当我从我的活动中调用它(创建通知)时 - 一切都很完美。当我使用指向活动当前实例的静态指针从服务调用它时 - MyActivity.CurrentInstance.CreateNotification(...) - 我的通知不会对滑动关闭事件做出反应。我什至尝试将 CreateNotification 的代码放入 RunOnUiThread - 没有结果。
因此,只有在我的活动中创建了该通知时,才会触发通知的滑动关闭事件。但是当收到来自 GCM 的消息时,我会创建通知。即使应用程序未运行,它实际上也会创建通知。
public void CreateNotification(........) {
//RunOnUiThread(() => {
var notificationBuilder = new Notification.Builder(this);
notificationBuilder.SetContentTitle(title);
notificationBuilder.SetContentText(description);
notificationBuilder.SetSmallIcon(Resource.Drawable.Icon);
var notificationIntent = new Intent(this, typeof(MainActivity));
notificationIntent.PutExtra(.......)
var contentIntent = PendingIntent.GetActivity(Application.Context, 0, notificationIntent, PendingIntentFlags.CancelCurrent);
notificationBuilder.SetContentIntent(contentIntent);
// Actually my headache
const String NOTIFICATION_DELETED_ACTION = "NOTIFICATION_DELETED";
var receiver = new MyBroadcastReceiver();
RegisterReceiver(receiver, new IntentFilter(NOTIFICATION_DELETED_ACTION));
Intent intent = new Intent(NOTIFICATION_DELETED_ACTION);
intent.PutExtra(.......)
var deleteIntent = PendingIntent.GetActivity(Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
notificationBuilder.SetDeleteIntent(deleteIntent);
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
notificationManager.Notify(1, notificationBuilder.Build());
//});
}
任何想法如何创建能够触发其滑动关闭事件的通知(在服务内部)?
【问题讨论】:
标签: android xamarin notifications broadcastreceiver notificationcenter