ZXing is not scanning on Android (Xamarin app) - xamarin

I am using below code to scan a QR code in my Xamarin. I am currently testing it on Samsung Galaxy (Android) and I am able to view the camera streaming but it is not scanning any QR code.
How can I fix this please to get the result of the QR scanned?
public void Scan()
{
try
{
scanner.Options = new MobileBarcodeScanningOptions()
{
UseFrontCameraIfAvailable = false, //update later to come from settings
PossibleFormats = new List(),
TryHarder = true,
AutoRotate = false,
TryInverted = true,
DelayBetweenContinuousScans = 2000,
};
scanner.VerticalOptions = LayoutOptions.FillAndExpand;
scanner.HorizontalOptions = LayoutOptions.FillAndExpand;
// scanner.IsVisible = false;
scanner.Options.PossibleFormats.Add(BarcodeFormat.QR_CODE);
// scanner.Options.PossibleFormats.Add(BarcodeFormat.DATA_MATRIX);
// scanner.Options.PossibleFormats.Add(BarcodeFormat.EAN_13);
scanner.OnScanResult += (result) => {
// Stop scanning
scanner.IsAnalyzing = false;
scanner.IsScanning = false;
if (scanner.IsScanning)
{
scanner.AutoFocus();
}
// Pop the page and show the result
Device.BeginInvokeOnMainThread(async () => {
if (result != null)
{
await DisplayAlert("Scan Value", result.Text, "OK");
}
});
};
mainGrid.Children.Add(scanner, 0, 1);
}
catch (Exception ex)
{
DisplayAlert("Scan Value", ex.ToString(), "Error");
}
}

Maybe you are using the wrong event handler, or missing an event, also the camera never focuses:
the condition is never true, due to this fragment of code:
scanner.IsScanning = false;
if (scanner.IsScanning)
{
scanner.AutoFocus();
}

Related

Xamarin - Switch statement for Follow and unFollow

I'm trying to make a follow and unfollow techniques to user profile
I made this code but the main problem is that the user followed successfully but if you tap the button again the toast will show that unfollowed and the button image will change (like you will follow again) but if you refresh the following image show again it's like nothing happen
switch (BtnFollow?.Tag?.ToString())
{
case "Add": //Sent follow
BtnFollow.SetColor(Color.ParseColor(AppSettings.MainColor));
BtnFollow.SetImageResource(Resource.Drawable.ic_tick);
BtnFollow.Tag = "friends";
DataUser.IsFollowing = true;
Toast.MakeText(Context, Context.GetText(Resource.String.Lbl_Sent_successfully_followed),
ToastLength.Short)?.Show();
PollyController.RunRetryPolicyFunction(new List<Func<Task>> { () => RequestsAsync.User.FollowUnFollowUserAsync(UserId, true) });
break;
case "friends": //Sent un follow
BtnFollow.SetColor(Color.ParseColor("#444444"));
BtnFollow.SetImageResource(Resource.Drawable.ic_add);
BtnFollow.Tag = "Add";
DataUser.IsFollowing = false;
Toast.MakeText(Context, Context.GetText(Resource.String.Lbl_Sent_successfully_Unfollowed),
ToastLength.Short)?.Show();
PollyController.RunRetryPolicyFunction(new List<Func<Task>> { () => RequestsAsync.User.FollowUnFollowUserAsync(UserId, false) });
break;
}
var dataUser = GlobalContext?.MainFragment?.ArtistsAdapter?.ArtistsList?.FirstOrDefault(a => a.Id == DataUser.Id);
if (dataUser != null)
{
dataUser.IsFollowing = DataUser.IsFollowing;
GlobalContext.MainFragment.ArtistsAdapter.NotifyDataSetChanged();
}
}
catch (Exception exception)
{
Methods.DisplayReportResultTrack(exception);
}
}
and this code to check the following status
if (DataUser.IsFollowing != null && DataUser.IsFollowing.Value) // My Friend
{
BtnFollow.SetColor(Color.ParseColor(AppSettings.MainColor));
BtnFollow.SetImageResource(Resource.Drawable.ic_tick);
BtnFollow.Tag = "friends";
}
else //Not Friend
{
BtnFollow.SetColor(Color.ParseColor("#444444"));
BtnFollow.SetImageResource(Resource.Drawable.ic_add);
BtnFollow.Tag = "Add";
}
}

Geolocation functionality of Xamarin Essentials wrong location results

I am using the Geolocation functionality of Xamarin Essentials in my app as a foreground service running all the time and I have noticed on several devices that I sometimes get locations which are really far away from where they should actually be, looking like this (the marked location is far away from the real location):
public async Task Run(CancellationToken token)
{
await Task.Run(async () => {
while (!stopping)
{
token.ThrowIfCancellationRequested();
try
{
await Task.Delay(2000);
var request = new GeolocationRequest(GeolocationAccuracy.Best);
var location = await Geolocation.GetLocationAsync(request);
if (location != null)
{
var message = new LocationMessage
{
Latitude = location.Latitude,
Longitude = location.Longitude
};
Device.BeginInvokeOnMainThread(() =>
{
MessagingCenter.Send<LocationMessage>(message, "Location");
});
}
}
catch (Exception ex)
{
Device.BeginInvokeOnMainThread(() =>
{
var errormessage = new LocationErrorMessage();
MessagingCenter.Send<LocationErrorMessage>(errormessage, "LocationError");
});
}
}
return;
}, token);
}
result

How can i add a custom video in broadcast in opentok

I wanted to add video while broadcasting.
To do this i am refering this link :
https://github.com/opentok/opentok-web-samples/tree/main/Publish-Video
After OT.initPublisher i am publishing this publisher in to session session.publish
But video is not showing in livestreaming.
Can anybody help me with this?
We can Publish custom audio source and video source from Video Element, using the captureStream() / mozCaptureStream() methods
Like mentioned in the below code snip
const contentVideoElement = document.createElement('VIDEO');
let screenPublisher = null;
contentVideoElement.autoplay = true;
contentVideoElement.controls = true;
contentVideoElement.classList.add('cameraContainer');
const url = URL.createObjectURL(file); // choose video file from input file control
contentVideoElement.src = url;
try {
await contentVideoElement.play();
} catch (error) {
console.log(error);
return;
}
let mediaStream = null;
if (contentVideoElement.captureStream) {
mediaStream = contentVideoElement.captureStream();
} else if (contentVideoElement.mozCaptureStream) {
mediaStream = contentVideoElement.mozCaptureStream();
} else {
console.error('Stream capture is not supported');
mediaStream = null;
return;
}
const videoTracks = mediaStream.getVideoTracks();
const audioTracks = mediaStream.getAudioTracks();
if (videoTracks.length > 0 && audioTracks.length > 0) {
const el = document.createElement('div');
screenPublisher = window.OT.initPublisher(
'content-video-element-id',
{
insertMode: 'append',
videoSource: videoTracks[0],
audioSource: audioTracks[0],
fitMode: 'contain', // Using default
width: '100%',
height: '100%',
showControls: false,
name:`Guest (Video)`,
},
(error) => {
if (error) {
contentVideoElement.pause();
console.log(error);
} else {
contentVideoElement.play();
openToksession.publish(screenPublisher, (error) => {
if (error) {
console.log(error);
} else {
// write here code after success publish video stream
}
});
}
},
);
screenPublisher.on({
streamDestroyed: ({ stream }) => {
contentVideoElement.pause();
},
});
contentVideoElement.addEventListener(
'ended',
() => {
console.log('Shared video ended');
},
false,
);
}
For capture MediaStream in reactjs: click here

Flash Light and other buttons not visible in ZXing.Mobile.MobileBarcodeScanner

I am using below code to scan bar codes. I have set the cancel and flash buttons texts but its not visible on the UI. Its working fine in iOS but not in Android.
See below code
public async Task StartScan()
{
var scanPage = new ZXing.Mobile.MobileBarcodeScanner();
this.cancelTimer = new CancellationTokenSource();
scanPage.AutoFocus();
scanPage.TopText = "Place the barcode between the red line";
scanPage.CameraUnsupportedMessage = "Camera doesnt supports AUTOFOCUS.";
scanPage.BottomText = "If it doesnt autofocus, touch the screen to autofocus";
scanPage.CancelButtonText = "<< Back";
scanPage.FlashButtonText = "Turn Flash";
scanPage.UseCustomOverlay = false;
Device.StartTimer(new TimeSpan(0, 0, 0, 3, 0), () =>
{
scanPage.AutoFocus();
// scanPage.BottomText = "focusing";
return true;
});
ZXing.Result result = null;
CancellationTokenSource cts = this.cancelTimer;
TimeSpan ts = new TimeSpan(0, 0, 0, 2, 0);
Device.StartTimer(ts, () =>
{
if (cts.IsCancellationRequested)
{
return false;
}
if (result == null)
{
scanPage.AutoFocus();
return true;
}
return false;
});
result = await scanPage.Scan(new MobileBarcodeScanningOptions
{
TryHarder = false,
AutoRotate = false,
UseNativeScanning = true,
PossibleFormats = GetAvailableFormats(),
});
if (result != null && !string.IsNullOrWhiteSpace(result.Text))
{
await Stop();
await ProcessResult(result.Text);
}
await Stop();
}
So from the above code, Bottom and Top texts are appearing but not the buttons for which code is like below.
scanPage.CancelButtonText = "<< Back";
scanPage.FlashButtonText = "Turn Flash";
Can anyone help me to get this?

Set Image Source on return from Gallery/Camera?

I have an Image view I'm having trouble setting the source for. I'm using a button to execute a TakePictureCommand which calls the TakePicture() method (shown below) which in turn sets my source "ImageSource". Debugging the method shows the image is coming in, but I never see it come up in the UI.
I may not be setting the binding for the Image properly, this is what I have:
Image avatar = new Image();
avatar.Source = ImageSource;
Button setImageBtn = new Button{ Text = "Photo" };
setImageBtn.Clicked += async (sender, e) =>
{
string action = await DisplayActionSheet(
"Event Photo", "Cancel", null, OPTION_CAMERA, OPTION_GALLERY);
if(action == OPTION_CAMERA) {
TakePictureCommand.Execute(null);
}
else if(action == OPTION_GALLERY) {
SelectPictureCommand.Execute(null);
}
};
TakePicture()
private async Task<MediaFile> TakePicture()
{
Setup();
ImageSource = null;
return await _mediaPicker.TakePhotoAsync(
new CameraMediaStorageOptions {
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
}).ContinueWith(t =>
{
if (t.IsFaulted)
{
Status = t.Exception.InnerException.ToString();
}
else if (t.IsCanceled)
{
Status = "Canceled";
}
else
{
var mediaFile = t.Result;
ImageSource = ImageSource.FromStream(() => mediaFile.Source);
return mediaFile;
}
return null;
}, _scheduler);
}
What am I missing here?
Below approach is working for me:
First, in XAML I added Image view
<Image Source="{Binding ImageSource}" VerticalOptions="Fill" HorizontalOptions="Fill"
Aspect="AspectFit"/>
Second, in ViewModel I added ImageSource property like this:
public ImageSource ImageSource
{
get { return _imageSource; }
set { this.SetProperty(ref _imageSource, value); }
}
Third, in command handler:
await TakePicture ();
Forth, code of TakePicture() method the same as you wrote.
My Setup():
if (_mediaPicker != null)
return;
var device = Resolver.Resolve<IDevice>();
_mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;

Resources