我有一个Xamarin.Forms应用程序,其类派生自GcmServiceBase,用于检索Android中的通知。
此类的OnMessage方法包括以下代码:
string messageText = intent.Extras.GetString("message");
if (!string.IsNullOrEmpty(messageText))
{
MessagingCenter.Send<INotifier, AlertModel>
(this, "myalert", new AlertModel(messageText));
CreateNotification("this is a notification...", messageText, context);
}
private void CreateNotification(string title, string desc, Context context)
{
var intent = new Intent(context, typeof(MainActivity));
const int pendingIntentId = 0;
var pendingIntent = PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent);
Notification.Builder builder = new Notification.Builder(context)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(desc)
.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
.SetSmallIcon(Resource.Drawable.Icon);
var notification = builder.Build();
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
但这引起了一个问题。当我单击状态栏中的通知时,它会再次创建页面,因此警报的订阅者会多次订阅。
MessagingCenter.Subscribe<INotifier, AlertModel> (this, "myalert",
(s,arg) => { //Handle });
我的问题是如何获取页面的现有实例,而不是每次都创建一个新实例?或者,如果处理页面有最佳实践 - 我应该将所有页面都设置为Singleton或其他类似的东西吗?还是以其他方式解决这个问题?
答案 0 :(得分:1)
我明白了。诀窍是在MainActivity类中将LaunchMode添加为SingleTop,如下所示:
[Activity (Label = "MyApp", LaunchMode =LaunchMode.SingleTop, Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
然后在创建通知的PendingIntent时传递onMessage请求发送的意图。所以CreateNotification方法现在看起来像:
private void CreateNotification(string title, string desc, Context context, Intent intent)
{
var pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.OneShot);
Notification.Builder builder = new Notification.Builder(context)
.SetAutoCancel(true)
.SetContentIntent(pendingIntent)
.SetContentTitle(title)
.SetContentText(desc)
.SetDefaults(NotificationDefaults.Sound | NotificationDefaults.Vibrate)
.SetSmallIcon(Resource.Drawable.Icon);
var notification = builder.Build();
var notificationManager = GetSystemService(Context.NotificationService) as NotificationManager;
const int notificationId = 0;
notificationManager.Notify(notificationId, notification);
}
这意味着每次都不会重新创建主要活动:
与'standard'的区别在于,如果活动实例已存在于当前任务的顶部且系统路由意图此活动,则不会创建新实例,因为它将触发onNewIntent()方法而不是创建一个新对象。我们以Twitter-oauth集成为例。 https://www.mobomo.com/2011/06/android-understanding-activity-launchmode/