问题描述
我知道这些问题是关于SO的多次询问。但是我无法解决这个问题。在我的xamarin.forms应用程序中,我正在使用自定义“相机视图”在一页内显示相机。拍照按钮位于共享代码中。为了从共享代码中拍照,我正在使用消息中心。当我们单击该按钮时,从共享代码发送的邮件中心将订阅我的相机自定义渲染,并且将进行拍照操作。
我面临的问题是消息传递中心的订阅部分将被击中多次。奇怪的是,每次单击按钮时,订阅都会增加。我添加了退订消息传递中心。然后它将不再命中。这是什么原因造成的?任何帮助表示赞赏。
我的共享代码部分,消息传递中心发送到该部分。
private async void Capture_Tapped(object sender,EventArgs e)
{
try
{
MessagingCenter.Send<CameraPopup>(this,"CaptureClick");
}
catch (Exception)
{
}
}
Android Camera Custom渲染上的会议中心订阅部分
protected async override void OnElementChanged(ElementChangedEventArgs<Centraverse.Views.Clocking.CustomCamera.CameraPreview> e)
{
base.OnElementChanged(e);
if (Control == null)
{
cameraPreview = new CameraPreview(Context);
SetNativeControl(cameraPreview);
// This portion hitting multiple times
MessagingCenter.Subscribe<CameraPopup>(this,"CaptureClick",(sender) =>
{
try
{
Log.Info("Reached here:","Try catch of first ");
if (DetectedFaceCount == 0)
{
//Do Action
}
else if (DetectedFaceCount == 1)
{
Control.Preview.StopFaceDetection();
Task.Run(() => takepicture());
}
else if (DetectedFaceCount > 1)
{
//Do Action
}
}
catch (Exception ex)
{
return;
}
// MessagingCenter.Unsubscribe<CameraPopup>(this,"CaptureClick");
});
}
if (e.OldElement != null)
{
}
if (e.NewElement != null)
{
try
{
Control.Preview = Camera.Open((int)e.NewElement.Camera);
Device.BeginInvokeOnMainThread(async () =>
{
Control.Preview.SetFaceDetectionListener(this);
Control.Preview.StartFaceDetection();
});
}
catch (Exception ex)
{
return;
}
}
}
解决方法
根据您的描述和代码,可能只有一个原因-您多次订阅该活动。因此,您需要先取消订阅或拥有某种已订阅的内部跟踪机制,然后只进行一次。