I'm trying to send a UDP broadcast on the Hololens but for some reason the thread won't get executed. Interestingly, when I compile it on my old laptop in VS it works?! I compared the installed SDK, settings everything but I cannot figure out why it works when I compile it on my old laptop. It was a mere coincidence that I discovered that in the first place.
This calls the thread:
public void StartThread()
{
// create thread for reading UDP messages
readThread = new Thread(new ThreadStart(ReceiveData));
readThread.IsBackground = true;
readThread.Start();
}
And the thread looks like this:
private void ReceiveData()
{
client = new UdpClient(port);
client.EnableBroadcast = true;
Debug.Log("Thread Started");
while (true)
{
try
....
The debug line won't even get executed. I works in Unity but not on Hololens, except I compile it on an old machine of mine.
Any thoughts? I'm at total loss here.
As derHugo suggested, the thread needed to be started like
public void StartThread()
{
// create thread for reading UDP messages
readThread = new Thread(ReceiveData);
readThread.IsBackground = true;
readThread.Start();
}
That did the trick.
I'm trying to request a permission at runtime for my app. I use a service provider to talk between the portable class and Android.
I start by calling this code on button press in the PCL:
using (new Busy(this))
{
var locationHelper = scope.Resolve<ILocationHelper>();
locationHelper.GetLocation(this);
}
This calls my Android level service:
public class AndroidLocationHelper : ILocationHelper, ILocationListener
{
readonly string[] PermissionsLocation =
{
Manifest.Permission.AccessCoarseLocation
};
const int RequestLocationId = 0;
public void GetLocation(SearchViewModel viewModel)
{
try
{
const string permission = Manifest.Permission.AccessCoarseLocation;
if (((int)Build.VERSION.SdkInt < 23) || (CheckSelfPermission(permission) == Permission.Granted))
{
}
else
RequestPermissions(PermissionsLocation, RequestLocationId);
}
catch (Exception ex)
{
Debug.WriteLine("Error while getting Location service");
Debug.WriteLine(ex.Message);
Messaging.AlertUser("There was an error with determining your location");
}
}
However, I get two errors on CheckSelfPermission and RequestPermissions. These two methods are only available to activities. The code works fine in MainActivity; however, I want to ask for permissions when the user hits a button, not in OnCreate or OnResume, etc.
Thanks for any help.
In your Android project, You can use this and use the Dependency Service to call it in Xamarin.Forms PCL project later:
var thisActivity = Forms.Context as Activity;
ActivityCompat.RequestPermissions(thisActivity, new string[] {
Manifest.Permission.AccessFineLocation }, 1);
ActivityCompat.RequestPermissions(thisActivity,
new String[] { Manifest.Permission.AccessFineLocation },
1);
You can try with ContextCompat.CheckSelfPermission, passing the application context, like this:
ContextCompat.CheckSelfPermission(Android.App.Application.Context, permission)
Update
In case of ActivityCompat.RequestPermissions, which requires an activity reference, you can keep track of the current activity. There is a very handy lib for that, called "CurrentActivityPlugin". You can find at https://github.com/jamesmontemagno/CurrentActivityPlugin
Rafael came up with a solution but I found another option that is a lot less effort just using MessagingCenter. In the MainActivity's OnCreate add a receiver that runs all the location code, that way you have access to all of the activities methods (and there are a bunch of tutorials on doing location services in MainActivity). Then add the Send inside of your service (the class).
To expound Rafael Steil's answer, I tried the suggested CurrentActivityPlugin and it worked on me. In my case I am trying to execute a voice call which needs CALL_PHONE permission. Here is the code snippet in your case: I used the ContextCompat & ActivityCompat so that I don't need to check the VERSION.SdkInt
using Plugin.CurrentActivity;
public void GetLocation(SearchViewModel viewModel){
var context = CrossCurrentActivity.Current.AppContext;
var activity = CrossCurrentActivity.Current.Activity;
int YOUR_ASSIGNED_REQUEST_CODE = 9;
if (ContextCompat.CheckSelfPermission(context, Manifest.Permission.AccessCoarseLocation) == (int)Android.Content.PM.Permission.Granted)
{
//Permission is granted, execute stuff
}
else
{
ActivityCompat.RequestPermissions(activity, new string[] { Manifest.Permission.AccessCoarseLocation }, YOUR_ASSIGNED_REQUEST_CODE);
}
}
It's dead simple
public bool CheckPermission()
{
const string permission = Manifest.Permission.ReceiveSms;
return ContextCompat.CheckSelfPermission(Forms.Context, permission) == (int) Permission.Granted;
}
Hope to find some guidance on this one soon, I've added reference for Windows IoT UWT in my project but still getting the following error ?
An exception of type 'System.TypeLoadException' occurred in test_led_alljoyn.exe but was not handled in user code
Additional information: Could not find Windows Runtime type 'Windows.Devices.Gpio.GpioController'.
Has anyone come across this issue while compiling applications for Raspberry Pi on Windows IoT core, on it's own one of my sample push button app works fine. Here's my code
public IAsyncOperation<testlightbulbSwitchResult> SwitchAsync(AllJoynMessageInfo info, bool interfaceMemberOn)
{
return (Task.Run(() =>
{
SwitchLED(interfaceMemberOn);
return testlightbulbSwitchResult.CreateSuccessResult();
}).AsAsyncOperation());
}
private void SwitchLED (bool state)
{
_ledState = state;
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.Gpio.GpioController"))
{
this.tController = GpioController.GetDefault();
if (this.tController == null)
{
//GpioStatus.Text = "There is no GPIO controller on this device.";
//return;
this.tPin = this.tController.OpenPin(5);
this.tPin.Write(GpioPinValue.High);
this.tPin.SetDriveMode(GpioPinDriveMode.Output);
}
this.tPin.Write(_ledState ? GpioPinValue.Low : GpioPinValue.High);
}
}
Solved. I had to set build platform target compile with .net native tool chain.
I've an application in Windows forms that connects to 16 serialports. The structure I used for each one is:
private void Serial_CodeNip_15_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
string S = Serial_CodeNip_15.ReadExisting();
myProcess(S);
}
public delegate void del_myProcess(string stringa);
private void myProcess(string stringa)
{
if (this.InvokeRequired)
{
del_myProcess tmp = new del_myProcess(myProcess);
try
{
this.Invoke(tmp, stringa);
}
catch (Exception)
{
}
}
else
{
// my code here
}
}
Receiving data from barcode readers, works fine until more Readers (up 6 or 7) start reading at the same time. In this cases my application tends to hang and all readers denotes a difficult to catch data from serial input buffers. Is this the correct way to read async data from serialports or there’s another simple way to do that. I noticed that working with few serialports there’s no problem.
Thank you in advance for helping
I am doing a windows service (call it SampleService), every is fine. When I started then stopped service through Windows Service Management Tool (service.msc), it run properly.
But my service will be request Start and Stop by another application. So I will not use Windows Service Management Tool in this case.
This is my service implement.
using System.ServiceProcess;
public partial class SampleService : ServiceBase
{
public SampleService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
this.WriteLog("OnStart");
// Doing start service logic down here
// Some service logic like create some files.
// Or just leave it empty like a brand new Windows Service.
}
protected override void OnStop()
{
this.WriteLog("OnStop");
// Doing clean service logic down here.
// Some service logic like: delete files.
// Or just leave it empty like a brand new Windows Service.
}
static readonly object synObject = new object();
public void WriteLog(string message)
{
if (string.IsNullOrEmpty(message))
{
return;
}
// Write log.
lock (synObject)
{
using (var wr = new StreamWriter(#"C:\logfile.txt", true))
{
wr.WriteLine(DateTime.Now + "-" + message);
}
}
}
}
And this is code logic use to Start and Stop service inside my another application. I can not modify this another application. The bellow source code simulate what happen.
class Program
{
static void Main(string[] args)
{
ServiceController sc = new ServiceController("SampleService");
// start service
sc.Start();
// doing some logic cost deltaTime or just stand by in deltaTime.
Thread.Sleep(deltaTime);
try
{
// stop service first time, nothing happen.
sc.Stop();
}
catch
{
}
try
{
// stop service second times, by dump people or apllication.
sc.Stop();
}
catch
{
// It got an exception here: "The service cannot accept control messages at this time".
// But the service did stopped.
}
}
}
The problem is:"When deltaTime is too short (bellow 3000ms with empty OnStart(), OnStop()), Service will stop incorrectly. The output log OnStop will never show up, that mean OnStop method did not called.
My service will doing clean up work in OnStop (like delete some file), but if it not be called, these files still there.
I cannot change logic of another application but I can change SampleService.
I want to ask:
Is this an Windows Service base issue and I cant do anything with it?
What ever it is, can I do clean up some where else?
Thank you!