How to check if device has flashlight - xamarin.forms

I need to check if device has a flash light.
I know I can switch it off and on with Xamarin Essentials.
await Flashlight.TurnOnAsync();
// Turn Off
await Flashlight.TurnOffAsync();
But I can't seem to find out how to only check if its present ?
Many iPads in iOS doesn't have it and

You can use the FeatureNotSupportedException exception:
try
{
// Turn On
await Flashlight.TurnOnAsync();
// Turn Off
await Flashlight.TurnOffAsync();
}
catch (FeatureNotSupportedException fnsEx)
{
// Handle not supported on device exception
//This exception is called when the device does not have a flashlight
}
catch (PermissionException pEx)
{
// Handle permission exception
}
catch (Exception ex)
{
// Unable to turn on/off flashlight
}
https://learn.microsoft.com/en-us/xamarin/essentials/flashlight?tabs=android

Related

Catch Socket Exception [duplicate]

This is probably a noob question, but how do I make my response throw an exception if the user does not have an internet connection or if it takes too long to fetch the data?
Future<TransactionModel> getDetailedTransaction(String crypto) async {
//TODO Make it return an error if there is no internet or takes too long!
http.Response response = await http.get(crypto);
return parsedJson(response);
}
You should surround it with try catch block, like so:
import 'package:http/http.dart' as http;
int timeout = 5;
try {
http.Response response = await http.get('someUrl').
timeout(Duration(seconds: timeout));
if (response.statusCode == 200) {
// do something
} else {
// handle it
}
} on TimeoutException catch (e) {
print('Timeout Error: $e');
} on SocketException catch (e) {
print('Socket Error: $e');
} on Error catch (e) {
print('General Error: $e');
}
Socket exception will be raised immediately if the phone is aware that there is no connectivity (like both WiFi and Data connection are turned off).
Timeout exception will be raised after the given timeout, like if the server takes too long to reply or users connection is very poor etc.
Also don't forget to handle the situation if the response code isn't = 200.
You don't need to use http to check the connectivity yourself, simply use connectivity library
You can use this plugin https://pub.dev/packages/data_connection_checker
So you can check prior if you have the connection, if not give a alert to the user that no internet connection. And if you have the internet connection then just proceed to your fetching part.
I will just link some resources below where it has been explained perfectly:
https://www.youtube.com/watch?v=u_Xyqo6lhFE
This is all things will be done prior to making an http call, but what if while making an http call the internet goes off then you can use the try catch block which #uros has mentioned.
Let me know if it works.
This is my approach to check internet connection to check internet connection throughout full app
i create a common class called "connectivity" & use it everywhere in app to check connectivity.i use connectivity package by flutter.
My connectivity class
Future<bool> check() async {
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.mobile) {
return true;
} else if (connectivityResult == ConnectivityResult.wifi) {
return true;
}
return false;
}
then i use this class like this:
#override
void initState() {
super.initState();
checkInternetConnection().then((internet) {
if (internet != null && internet) {
// Internet Present Case
// do your task;
} else {
// No-Internet Case
showAlertDialog(context);
}
});
}

Plugin BLE (v1.3.0) delay after characteristic.ReadAsync()

I’m developing an app and I want to read some characteristics one after one.
My issue is that after a read is done I must do a delay otherwise I get an error.
Why does it need a delay ? is there a way to write correctly read tasks one after other ?
I'm using Xamarin.forms and Ble v1.3.0 plugin.
I've tried "await Task.Delay(200)" between two consecutive ReadAsync() functions and it works fine but if I remove the delay, the second ReadAsync gets exception.
private async Task ReadChr(ICharacteristic LocalCharacteristic)
{
byte[] localData = { };
if (LocalCharacteristic.CanRead)
{
try
{
return localData = await LocalCharacteristic.ReadAsync();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}
if (firstCharacteristic.CanRead)
{
var ccc = await ReadChr(firstCharacteristic);
}
await Task.Delay(200);
if (secondCharacteristic.CanRead)
{
var ddd = await ReadChr(secondCharacteristic);
}
I'm searching something like polling the read process status of the characteristic. Delay after ReadAsync does not seem a good practice coding.
Any idea ?

Task Cancel exception for an api call in Xamain.Forms for iOS real device only

I am doing an app in which i am calling a web api. I am getting task cancel exception when i call the api in iPad/iPhone.But the response is fine in simulator and android devices.Can anyone please help me in resolving the issue.I am not able to fine where it is going wrong.
Thanks in advance.
Try using Native Http Handler to see it improves.
Declare an interface.
public interface IHttpHandler
{
HttpClient ReturnHandler();
}
Implement it this way.
public class HttpHandler : IHttpHandler
{
public HttpClient ReturnHandler()
{
try
{
var client = new HttpClient(new NSUrlSessionHandler()
{
});
client.Timeout = TimeSpan.FromSeconds(120);
return client;
}
catch (TaskCanceledException ex)
{
Console.WriteLine("TaskCanceledException ReturnHandler-->" + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("TaskCanceledException ReturnHandler-->" + ex.InnerException.Message);
}
return null;
}
catch (Exception ex)
{
Console.WriteLine("ReturnHandler Exception-->" + ex.Message);
if (ex.InnerException != null)
{
Console.WriteLine("ReturnHandler Exception-->" + ex.InnerException.Message);
}
return null;
}
}
}
Use Xamarin forms inbuilt Dependency injection to utilise the interface I gave you to have HTTPClient with native handler.
If you don't know how to read Here

azure notification issue: apns works while template not response

Follow this tutorial "Add push notifications to your Xamarin.Forms app" for Xamarin.Forms development. After insert notification code in Azure backend and iOS, the notification template send out but no alert on device. However, the test sending of APNS shows the alert on the device. Appreciate any suggestion.
Here is my RegisteredForRemoteNotifications
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
const string templateBodyAPNS = "{\"aps\":{\"alert\":\"$(message)\"}}";
JObject templates = new JObject();
templates["genericMessage"] = new JObject
{
{"body", templateBodyAPNS}
};
/*
// Register for push with your mobile app
Push push = TodoItemManager.DefaultManager.CurrentClient.GetPush();
try
{
push.RegisterAsync(deviceToken, templates);
}
catch (System.Exception ex)
{
Debug.WriteLine(#"Register error: {0}", ex.Message);
}
*/
Hub = new SBNotificationHub(Constants.ConnectionString, Constants.NotificationHubName);
Hub.UnregisterAllAsync(deviceToken, (error) => {
if (error != null)
{
Console.WriteLine("Error calling Unregister: {0}", error.ToString());
return;
}
NSSet tags = new NSSet(); // create tags if you want
var expire = DateTime.Now.AddDays(90).ToString(); // set expire
try
{
//register native notification
Hub.RegisterNativeAsync(deviceToken, tags, (errorCallback) =>
{
if (errorCallback != null)
Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
//register template notification
Hub.RegisterTemplateAsync(deviceToken, "add_newbook_notification", templateBodyAPNS, expire, tags, (errorCallback) => {
if (errorCallback != null)
Console.WriteLine("RegisterNativeAsync error: " + errorCallback.ToString());
});
}
catch (System.Exception ex)
{
Debug.WriteLine(#"Register error: {0}", ex.Message);
}
});
}
Because there could be multiple notification registration in one client app, theoretically both native and template notification registration should succeed here. However, I only receive the APNS but no template.
Azure Messaging - RegisterTemplateAsync isn't working? This link solves my problem.
Note:
The problem was that this ExpiryTemplate wasn't clear for me. I did find any docs on that one, but apparently, it's a DateTime formatted
as en-us.
The expiry datetime MUST be formatted as en-us. Otherwsie, the RegisterTemplateAsync can't work.

Xamarin Forms WinPhone 8.1 Silverlight WNS push notifications

I'm attempting to configure my app to use WNS instead of MPNS (I am using Xamarin Forms and have a Win Phone 8.1 Silverlight project with an Azure Notification hub for the back end), for that I updated my code to use the the mobile service to register the phone for push notifications and changed the Notification Service in the WMAppManifest.xml to WNS. After implementing these changes when I check the phones registration through azure it says its MPNS. Below are some screen captures of my configuration and code snippets of how im registering the app.
WMAppManifest.xml
Package.appxmanifest
NotificationManager Code
public class PushNotificationManager : IPushNotificationManager
{
private PushNotificationChannel channel;
public PushNotificationManager() { }
public static MobileServiceClient MobileService = new MobileServiceClient(Utilities.Constants.ApplicationURL, Utilities.Constants.ApplicationKey);
public async Task RegisterDevice()
{
try
{
channel = await PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync();
channel.PushNotificationReceived += Channel_PushNotificationReceived;
await this.RegisterWinDevice(channel.Uri);
NotificationTask.UnregisterBackgroundTask();
NotificationTask.RegisterBackgroundTask();
}
catch (Exception ex)
{
throw ex;
}
}
protected void Channel_PushNotificationReceived(PushNotificationChannel sender, PushNotificationReceivedEventArgs args)
{
try
{
//Create notification
}
catch (Exception ex)
{
throw ex;
}
}
public async Task UnregisterDevice()
{
if(channel != null)
{
channel.Close();
}
await MobileService.GetPush().UnregisterNativeAsync();
}
private async Task RegisterWinDevice(string channelUri)
{
try
{
var tags = new List<string>() { };
User user = LocalStorage.GetUserInfo();
tags.Add(user.Id.ToString());
await MobileService.GetPush().RegisterNativeAsync(channelUri, tags.ToArray());
}
catch (Exception ex)
{
throw ex;
}
}
private void CreateNotification(string title, string message)
{
//Show Toast
}
}
In azure I have set the windows Package SID and client secret. I also have unauthenticated push notifications enabled (Although from my understanding this is for MPNS).
And finally here's a screen capture of how it registers with the following code:
If anyone has any idea how to get it to properly register to WNS I'd greatly appreciate the help. Thanks!
Just an update as to how I resolved my problem in case anyone comes across this. I had to switch my winphone project to a non silverlight application (I'm guessing its not supported with this version). Once I did this everything started working correctly.

Resources