Xamarin polling without stuck - xamarin

I am implementing an APP with Xamarin.
The app need to refresh data through Wi-Fi with device and show new data on screen.
But when polling triggered. The app always stuck for few seconds.
protected async override void OnAppearing()
{
//Show new data when entering this page
await Polling();
}
async Task Polling()
{
await Read_Data();
Show_Data();
}
How could I do this without stuck. Make the app polling smoothly?
I want to call the Polling() every 30 seconds.
Thank you!

Related

Google Play Store internal test - app stuck on splash screen

I have created an internal test for an app using the Google Play Console and sent the hyperlink to a test user. However, once the app is installed on the tester's phone and the Open button is tapped it gets stuck on the splash screen and will not go any further. The tester has tried restarting the phone, Force Stop the Google Play app, Clear Data and Clear Cache for Google Play app, uninstall/reinstall the app. None of these have helped. What would cause this behavior? What steps should I take next to debug/resolve this issue?
i solved my problem by putting try block before runApp(MyApp()) in main
void main() async {
WidgetsFlutterBinding.ensureInitialized();
try {
final InitialController _initialController = Get.put(InitialController(), permanent: true);
final BasketController _basketController = Get.put(BasketController(), permanent: true);
//final BackInterceptorController _backInterceptorController = Get.put(BackInterceptorController(), permanent: true);
await _initialController.tokenInit();
} catch (e) {
logger(e);
}
runApp(MyApp());
}

nativescript-phone prevents Nativescript-contacts from returning

I have an app where I want to select a person from contacts and then send a text to that person. It works as expected for the first user, but after that the app never receives control after the contact is selected. I've isolated the problem to the Nativescript-phone plugin. If you simply call phone.sms() to send a text, and then call contacts.getContact(), the problem occurs. I see this on both Android and iOS.
I've created a sample app that demos the problem at https://github.com/dlcole/contactTester. The sample app is Android only. I've spent a couple days on this and welcome any insights.
Edit 4/21/2020:
I've spent more time on this and can see what's happening. Both plugins have the same event handler and same request codes:
nativescript-phone:
var SEND_SMS = 1001;
activity.onActivityResult = function(requestCode, resultCode, data) {
nativescript-contacts:
var PICK_CONTACT = 1001;
appModule.android.on("activityResult", function(eventData) {
What happens is that after invoking phone.sms, calling contacts.getContact causes control to return to the phone plugin, and NOT the contacts plugin. I tried changing phone's request code to 1002 but had the same results.
So, the next step is to determine how to avoid the collision of the event handlers.
Instead of using activityResult event, nativescript-phone plugin overwrites the default activity result callback.
A workaround is to set the callback to it's original value after you are done with nativescript-phone.
exports.sendText = function (args) {
console.log("entering sendText");
const activity = appModule.android.foregroundActivity || appModule.android.startActivity;
const onActivityResult = activity.onActivityResult;
permissions.requestPermissions([android.Manifest.permission.CALL_PHONE],
"Permission needed to send text")
.then(() => {
console.log("permission granted");
phone.sms()
.then((result) => {
console.log(JSON.stringify(result, null, 4));
activity.onActivityResult = onActivityResult;
})
})
}

Edge extension: BackgroundTaskInstance cancels with SystemPolicy reason when DesktopBridge app tries to open WebSocket

I created an Edge browser extension which uses Native Messaging to a native app running via a Desktop Bridge technology. I used the SecureInput as a sample, which contains the Edge extension, UWP host and a Win32 Desktop Bridge app.
I need the Win32 Desktop Bridge app to connect to a web service using HTTP and WebSocket, so I added an internetClientServer and a privateNetworkClientServer capabilities to the package manifest, beside the already existed runFullTrust one.
The Win32 Desktop Bridge app activates just fine, and it is able to connect to the web server using HTTP. But as soon as it tries to open a WebSocket connection, the BackgroundTaskInstance on the UWP host receives a cancellation request with a BackgroundTaskCancellationReason.SystemPolicy as a reason, and the Desktop Bridge application closes. Unfortunately, the documentation for the BackgroundTaskCancellationReason.SystemPolicy does not explain much about true reasons of the cancellation request.
I tried to use two WebSocket classes: the System.Net.WebSockets.ClientWebSocket and the Windows.Networking.Sockets.MessageWebSocket, with the same result. No fancy code, just regular
var socket = new MessageWebSocket();
...
await socket.ConnectAsync(new Uri("wss://127.0.0.1:9001/myservice"));
The same WebSocket service endpoint is available from other WS clients, so I guess there is no server/firewall/antivirus issue here.
I also played with the CheckNetIsolation tool, adding loopback exemption for the Edge browser and for the package, with no effect. The HTTP works fine without the loopback exemption.
What may be a true reason of the task cancellation, and what can be a possible way to prevent it?
Ok, I resolved the issue. Thanks to this comment by Tom Shane I stumbled upon, I realized that the BackgroundTaskCancellationReason.SystemPolicy tells that the background task is closed by the system to release some system resources, and that in my case it happened because I didn't obtain a deferral in my async event handler. When the event handler yielded without a deferral, the system decided it can shut the task down. Below is a digested version of the code:
static class Program
{
static AppServiceConnection connection = null;
[STAThread]
static void Main(string[] args)
{
Thread appServiceThread = new Thread(new ThreadStart(ThreadProc));
appServiceThread.Start();
Application.Run();
}
static async void ThreadProc()
{
try {
connection = new AppServiceConnection();
connection.AppServiceName = "...";
connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
connection.RequestReceived += OnRequestReceived;
connection.ServiceClosed += OnServiceClosed;
var status = await connection.OpenAsync();
....
}
catch (Exception e) { ... }
}
private static async void OnRequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
var defer = args.GetDeferral(); // <== that was missing, rookie mistake!
try {
var msg = ParseMessage(args.Request.Message);
if (msg.type.Equals("ws")) {
// this method was truly async
// and every time it yielded the issue was revealed
await HandleWsMessage(request, msg);
}
else if (msg.type.Equals("http")) {
// but this method was actually synchronous despite being marked as "async"
// and it never yielded, masking the issue for HTTP client
await HandleHttpMessage(request, msg);
}
}
catch (Exception e) { ... }
finally {
defer.Complete();
}
}
}

Bot Framework v3 Dialog returning Cards

I am digging through all the great new stuff in v3 of the bot framework. One of the things that I am trying to do is create a dialog that responds with cards. But I cannot find a sample that shows how to do this.
I've tried to monkey with it on my own but haven't had much luck. In most of their code samples for Dialogs you cast the Activity object you get in your Post to an IMessageActivity class. Then when you respond you do so with just plain text. All the examples with cards have you create an Activity class. However because I've cast it to IMessageActivity I can't use the CreateReply method. And if I can't do that then when I create an Activity I get an error that the 'activityId' cannot be null.
Any advice, thoughts, or insight would be greatly appreciated.
Thanks in advance!
I added this code to my dialog:
protected override async Task MessageReceived(IDialogContext context, IAwaitable<IMessageActivity> item)
{
_message = (Activity)await item;
await base.MessageReceived(context, item);
}
[field: NonSerialized()]
private Activity _message;
[LuisIntent("Ping")]
public async Task Ping(IDialogContext context, LuisResult result)
{
Activity replyToConversation = _message.CreateReply("Should go to conversation, with a carousel");
replyToConversation.Recipient = _message.From;
replyToConversation.Type = "message";
replyToConversation.AttachmentLayout = "carousel";
.
.
.
await context.PostAsync(replyToConversation);
context.Wait(MessageReceived);
}
I got it working in the emulator but not in Skype but I guess my problem is this one Rich Card attachments are not showing on web chat or Skype

Does xamarin.android support DownloadHelper?

The download is started by the user clicking on the Download File button. The Xamarin.Android application utilizes a ProgressBar widget to display the download progress.
The button that begins the download has the following asynchronous event handler assigned to it's Click event:
async void StartDownloadHandler(object sender, System.EventArgs e)
{
_progressBar.Progress = 0;
Progress<DownloadBytesProgress> progressReporter = new Progress<DownloadBytesProgress>();
progressReporter.ProgressChanged += (s, args) => _progressBar.Progress = (int)(100 * args.PercentComplete);
Task<int> downloadTask = DownloadHelper.CreateDownloadTask(DownloadHelper.ImageToDownload, progressReporter);
int bytesDownloaded = await downloadTask;
System.Diagnostics.Debug.WriteLine("Downloaded {0} bytes.", bytesDownloaded);
}
In the previous code snippet, the Progress encapsulates a lambda that will update ProgressBar, displaying the percentage of bytes that were downloaded. It is important to realize that Progress will execute in the same SynchronizationContext it which it was instantiated. So, because Progress is created on the UI thread, it will run in the UI thread. It is not necessary to explicitly use RunOnUIThread inside the provided lambda to update the UI.
I dont see DownloadHelper on xamarin.android. I want to create a download method

Resources