I'm trying to scan a QR Code from my Xamarin.Forms application but the QR Code isn't getting detected until i restart the scanner.
I'm using ZXing.Net.Mobile.Forms. Once the ScannerPage has been pushed on the navigation stack it requests the camera permissions. After fulfilling the request it has access to the camera but isn't scanning the QR Code. I tried changing the permission handler since it works after restarting the scanner after granting the permission, but that didn't work.
private async void createScanPageAsync()
{
#if __ANDROID__
// Initialize the scanner first so it can track the current context
MobileBarcodeScanner.Initialize (Application);
#endif
var options = new MobileBarcodeScanningOptions()
{
TryHarder = true,
};
var scanPage = new ZXingScannerPage()
{
Title = AppResources.scanPageTitle,
DefaultOverlayTopText = AppResources.scanPageTitle,
DefaultOverlayShowFlashButton = true
};
await Navigation.PushAsync(scanPage);
scanPage.OnScanResult += (scanResult) =>
{
scanPage.IsScanning = false;
Vibration.Vibrate();
QRCode scans = JsonConvert.DeserializeObject<QRCode>(scanResult.Text);
AppPreferences.Network.Ip = scans.ip;
AppPreferences.Network.Port = scans.port;
Device.BeginInvokeOnMainThread(async () =>
{
await Navigation.PopAsync();
});
};
}
}
The expected outcome would be a successful scan on the first try, but i only get a successful scan after granting permissions and then reopening the scanner page.
For me the Xamarin.Essentials did the trick. It has a permission plugin that can help you ask for permission and after that, you can then launch the scanner without problem
Related
I'm trying to capture a video of my application using UWP APIs, specifically the Windows.Media.AppRecording namespace. When I try to execute the code I get a CanRecord flag as false, and the reason given by the Details property is that "something" is disabled by the user.
How can I enable the screen capture? Do I need a specific configuration file, or manifest?
My application is as simple as it get: Just a WPF in .NET 4.7.2, consisting in a button to start recording and a button to stop recording.
Here is the method:
public async Task StartRecordingAsync(string fileName)
{
AppRecordingManager manager = AppRecordingManager.GetDefault();
var status = manager.GetStatus();
if (status.CanRecord || status.CanRecordTimeSpan)
{
var myVideo = await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos);
StorageFolder projectFolder = await myVideo.SaveFolder.CreateFolderAsync("DataFolder", CreationCollisionOption.OpenIfExists);
var audio = await projectFolder.CreateFileAsync(fileName, CreationCollisionOption.GenerateUniqueName);
var result = await manager.StartRecordingToFileAsync(audio).AsTask<AppRecordingResult>(CTS.Token);
if (result.Succeeded)
{
IsRecording = true;
}
else
{
IsRecording = false;
}
}
}
And here are the Details given by the status variable:
status.Details
The IsDisbaledByUser property of the AppRecordingStatusDetails is false when the user does not allow apps to record.
True if app recording has been disabled by the user; otherwise, false.
To allow apps to record, you need to enable Game Bar from Windows Settings:
Settings -> Gaming -> Record game clips, screenshots, and broadcast using Game bar
I'm trying to play the built-in webcam feed in a MediaElement within a UWP app. It works fine for a few users but there is no feed played for most and I'm lost on what could be the issue.
Some observations when the webcam feed doesn't play:
The code executes without any exceptions
The dialog that requests user permission to access the camera is shown
The LED indicating the webcam is in use turns on soon as it is executed, but there is no feed.
Skype and Camera apps work fine.
The app was working as expected until a week back. A few things that changed in the mean time that could have had an impact are
Installed Kaspersky
A bunch of windows updates
Uninstalled VS2017 professional edition & VS2019 Community edition and installed VS2019 Professional Edition
Some additional information that might be needed to narrow down the reason.
Webcam is enabled in the Package manifest of the app
App Target version: 18362
App Min version: 18362
Windows OS Version : 18362
Any help on this would be highly appreciated. Thanks much in advance!
Here is the piece of code used to play the webcam feed where VideoStreamer is a MediaElement.
private async Task PlayLiveVideo()
{
var allGroups = await MediaFrameSourceGroup.FindAllAsync();
var eligibleGroups = allGroups.Select(g => new
{
Group = g,
// For each source kind, find the source which offers that kind of media frame,
// or null if there is no such source.
SourceInfos = new MediaFrameSourceInfo[]
{
g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Front
&& info.SourceKind == MediaFrameSourceKind.Color),
g.SourceInfos.FirstOrDefault(info => info.DeviceInformation?.EnclosureLocation.Panel == Windows.Devices.Enumeration.Panel.Back
&& info.SourceKind == MediaFrameSourceKind.Color)
}
}).Where(g => g.SourceInfos.Any(info => info != null)).ToList();
if (eligibleGroups.Count == 0)
{
System.Diagnostics.Debug.WriteLine("No source group with front and back-facing camera found.");
return;
}
var selectedGroupIndex = 0; // Select the first eligible group
MediaFrameSourceGroup selectedGroup = eligibleGroups[selectedGroupIndex].Group;
MediaFrameSourceInfo frontSourceInfo = selectedGroup.SourceInfos[0];
MediaCapture mediaCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings()
{
SourceGroup = selectedGroup,
SharingMode = MediaCaptureSharingMode.ExclusiveControl,
MemoryPreference = MediaCaptureMemoryPreference.Cpu,
StreamingCaptureMode = StreamingCaptureMode.Video,
};
try
{
await mediaCapture.InitializeAsync(settings);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("MediaCapture initialization failed: " + ex.Message);
return;
}
var frameMediaSource1 = MediaSource.CreateFromMediaFrameSource(mediaCapture.FrameSources[frontSourceInfo.Id]);
VideoStreamer.SetPlaybackSource(frameMediaSource1);
VideoStreamer.Play();
}
As mentioned by Faywang-MSFT here , it worked after marking the application as trusted in Kaspersky.
I just converted one of my apps to target Android API 9 (was targeting API 8); now when notifications are sent out, the volume of media is lowered and never comes back to full volume.
The app uses WebView to play media files. This was not happening prior to targeting API 9. I had to convert the app into level 9 so that I could upload to the Google Play Store. I am running a Samsung S7 which was originally designed for API level 6 (with the OS upgraded to 8.0), not sure if that has something to do with the issue. Another detail is that I use Xamarin.Android for development, not sure if that matters either.
Additionally, I forced the notifications to play a blank sound (a very short[couple ms] blank mp3) in the same build that I converted the app to target API 9:
var channelSilent = new Android.App.NotificationChannel(CHANNEL_ID, name + " Silent", Android.App.NotificationImportance.High)
{
Description = description
};
var alarmAttributes = new Android.Media.AudioAttributes.Builder()
.SetContentType(Android.Media.AudioContentType.Sonification)
.SetUsage(Android.Media.AudioUsageKind.Notification).Build()
//blank is blank mp3 file with nothing in it, a few ms in duration
var uri = Android.Net.Uri.Parse("file:///Assets/blank.mp3")
channelSilent.SetSound(uri, alarmAttributes);
...so it could also be the blank sound that is causing the ducking to malfunction, not the API change. Is there something to do with notification sound ducking that could be causing the issue? Is there any other way to mute a notification with Xamarin.Android other than playing a blank sound? That is one route I think would be worth trying to fix this issue.
Here is the code I am using to generate notifications:
private static List<CustomNotification> _sentNotificationList = new List<CustomNotification>();
private static NotificationManagerCompat _notificationManager;
public async void SendNotifications(List<CustomNotification> notificationList)
{
await Task.Run(() =>
{
try
{
var _ctx = Android.App.Application.Context;
if (_notificationManager == null)
{
_notificationManager = Android.Support.V4.App.NotificationManagerCompat.From(_ctx);
}
if (notificationList.Count == 0)
{
return;
}
int notePos = 0;
foreach (var note in notificationList)
{
var resultIntent = new Intent(_ctx, typeof(MainActivity));
var valuesForActivity = new Bundle();
valuesForActivity.PutInt(MainActivity.COUNT_KEY, _count);
valuesForActivity.PutString("URL", note._noteLink);
resultIntent.PutExtras(valuesForActivity);
var resultPendingIntent = PendingIntent.GetActivity(_ctx, MainActivity.NOTIFICATION_ID, resultIntent, PendingIntentFlags.UpdateCurrent);
resultIntent.AddFlags(ActivityFlags.SingleTop);
var alarmAttributes = new Android.Media.AudioAttributes.Builder()
.SetContentType(Android.Media.AudioContentType.Sonification)
.SetUsage(Android.Media.AudioUsageKind.Notification).Build();
//I am playing this blank sound to prevent android from spamming sounds as the notifications get sent out
var uri = Android.Net.Uri.Parse("file:///Assets/blank.mp3");
//if the notification is the first in our batch then use this
//code block to send the notifications with sound
if (!_sentNotificationList.Contains(note) && notePos == 0)
{
var builder = new Android.Support.V4.App.NotificationCompat.Builder(_ctx, MainActivity.CHANNEL_ID + 1)
.SetAutoCancel(true)
.SetContentIntent(resultPendingIntent) // Start up this activity when the user clicks the intent.
.SetContentTitle(note._noteText) // Set the title
.SetNumber(1) // Display the count in the Content Info
.SetSmallIcon(Resource.Drawable.bitchute_notification2)
.SetContentText(note._noteType)
.SetPriority(NotificationCompat.PriorityMin);
MainActivity.NOTIFICATION_ID++;
_notificationManager.Notify(MainActivity.NOTIFICATION_ID, builder.Build());
_sentNotificationList.Add(note);
notePos++;
}
//if the notification isn't the first in our batch, then use this
//code block to send the notifications without sound
else if (!_sentNotificationList.Contains(note))
{
var builder = new Android.Support.V4.App.NotificationCompat.Builder(_ctx, MainActivity.CHANNEL_ID)
.SetAutoCancel(true) // Dismiss the notification from the notification area when the user clicks on it
.SetContentIntent(resultPendingIntent) // Start up this activity when the user clicks the intent.
.SetContentTitle(note._noteText) // Set the title
.SetNumber(1) // Display the count in the Content Info
.SetSmallIcon(Resource.Drawable.bitchute_notification2)
.SetContentText(note._noteType)
.SetPriority(NotificationCompat.PriorityHigh);
MainActivity.NOTIFICATION_ID++;
_notificationManager.Notify(MainActivity.NOTIFICATION_ID, builder.Build());
_sentNotificationList.Add(note);
notePos++;
}
ExtStickyService._notificationsHaveBeenSent = true;
}
}
catch
{
}
});
}
In my MainActivity I've created two different notification channels: one is silent; the other uses default notification setting for the device:
void CreateNotificationChannel()
{
var alarmAttributes = new Android.Media.AudioAttributes.Builder()
.SetContentType(Android.Media.AudioContentType.Sonification)
.SetUsage(Android.Media.AudioUsageKind.Notification).Build();
var uri = Android.Net.Uri.Parse("file:///Assets/blank.mp3");
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var name = "BitChute";
var description = "BitChute for Android";
var channelSilent = new Android.App.NotificationChannel(CHANNEL_ID, name + " Silent", Android.App.NotificationImportance.High)
{
Description = description
};
var channel = new Android.App.NotificationChannel(CHANNEL_ID + 1, name, Android.App.NotificationImportance.High)
{
Description = description
};
channel.LockscreenVisibility = NotificationVisibility.Private;
//here is where I set the sound for the silent channel... this could be the issue?
var notificationManager = (Android.App.NotificationManager)GetSystemService(NotificationService);
channelSilent.SetSound(uri, alarmAttributes);
notificationManager.CreateNotificationChannel(channel);
notificationManager.CreateNotificationChannel(channelSilent);
}
Full source: https://github.com/hexag0d/BitChute_Mobile_Android_BottomNav/tree/APILevel9
EDIT: something really interesting is that if I pulldown the system ui bar, the volume goes back to normal. Very strange workaround but it might help diagnose the cause.
DOUBLE EDIT: I used .SetSound(null, null) instead of using the blank .mp3 and the ducking works fine now. See comments
In Xamarin Forms, does the IsShowingUser property of Xamarin.Forms.Maps work for iOS?
I can get every aspect of my map to work on both Android and iOS, but the current location 'blue dot' does not show on iOS.
I'm setting this in shared code in the PCL project, just after successfully asking for permission to use location.
var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);
if (status != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Location });
status = results[Permission.Location];
}
if (status == PermissionStatus.Granted)
{
MyMap.IsShowingUser = true;
}
thanks
I can get every aspect of my map to work on both Android and iOS, but the current location 'blue dot' does not show on iOS.
It is because the map doesn't locate the current user location at that time, you can use Xam.Plugin.Geolocator to get your current location, and move the map to it.
var locator = CrossGeolocator.Current;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude),
Distance.FromMiles(1)));
I am using Xamarin forms to write an iOS app and using the ZXing library to scan barcodes. I am trying to read a driver's license (PDF417) barcode, but the library is not able to recognize that barcode.
If I include UPC or other barcodes in the PossibleFormats, they are scanned correctly.
I am also certain the barcode I am trying to read is PDF417 barcode because Scandit is able to recognize it correctly while using only PDF417 barcode.
Here is the code I am using. What do I need to change so that the PDF417 barcode is recognized correctly?
async void Handle_Clicked (object sender, System.EventArgs e)
{
MobileBarcodeScanningOptions options = new MobileBarcodeScanningOptions ();
options.PossibleFormats = new List<ZXing.BarcodeFormat> () {
ZXing.BarcodeFormat.PDF_417
};
options.TryHarder = true;
var scanPage = new ZXingScannerPage (options);
scanPage.OnScanResult += (result) => {
// Stop scanning
scanPage.IsScanning = false;
// Pop the page and show the result
Device.BeginInvokeOnMainThread (async () => {
await Navigation.PopAsync ();
await DisplayAlert ("Scanned Barcode", result.Text, "OK");
});
};
// Navigate to our scanner page
await Navigation.PushAsync (scanPage);
}
I ran into this exact same issue a few days ago and fixed it with the following. In the MobileBarcodeScanningOptions class there's a property of type CameraResolutionSelectorDelegate called CameraResolutionSelector. You can set this to return a higher camera resolution from a list of available resolutions. So my instantiation of MobileBarcodeScanningOptions looks like this:
var options = new MobileBarcodeScanningOptions {
TryHarder = true,
CameraResolutionSelector = HandleCameraResolutionSelectorDelegate,
PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.PDF_417 }
};
And my HandleCameraResolutionSelectorDelegate:
CameraResolution HandleCameraResolutionSelectorDelegate(List<CameraResolution> availableResolutions)
{
//Don't know if this will ever be null or empty
if (availableResolutions == null || availableResolutions.Count < 1)
return new CameraResolution () { Width = 800, Height = 600 };
//Debugging revealed that the last element in the list
//expresses the highest resolution. This could probably be more thorough.
return availableResolutions [availableResolutions.Count - 1];
}
That's all I needed to change to get a driver's license (PDF417) barcode to scan.
Here's the source code for MobileBarcodeScanningOptions.cs from ZXing github.