Windows Phone 8 Accelerometer events - c#

I'm making my first game for Windows Phone (XNA). I use Accelerometer to change the position of a crosshair on the screen:
Here is the code in my Initialize() function (note that Accelerometer is local variable declared only in this function):
Accelerometer accelerometer = new Accelerometer();
accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged;
accelerometer.Start();
And the event handler:
void accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
lock (accelerometerVectorLock)
{
accelerometerVector = new Vector3(
(float)e.SensorReading.Acceleration.X,
(float)e.SensorReading.Acceleration.Y,
(float)e.SensorReading.Acceleration.Z);
}
}
This works fine on Windows Phone Emulator, and on my Nokia Lumia 520 connected to the computer and launching from Visual Studio, however when I launch the game in the phone (not connected to the computer), the accelerometer_CurrentValueChanged event appears to be called only once, on application startup.
My solution was to make the accelerometer a member of my Game class, then code in Initialize() like this:
accelerometer = new Accelerometer();
accelerometer.CurrentValueChanged += accelerometer_CurrentValueChanged;
accelerometer.Start();
So my question is, why does this solution work? And why is there a difference between application launched from VS and normally, even on the same device?

Why this solution works?
This solution works because you're keeping a reference to the accelerometer. Windows Phone applications, like all .NET applications, use an automated system for memory management. A background process, called garbage collector, inspects the objects in a regular basis, detects those who are not referenced anymore, and clean them. If you declare accelerometer as a local variable, it won't be referenced anymore when the function exits, and will therefore be cleaned. When you declare it as a member of your class, it will be alive for as long as your class lives.
Why the difference between application launched from VS and normally, on the same device?
When launching the code from Visual Studio, a debugger is attached. To help you debugging, it has some impacts on the way the code executes. Notably, it makes the garbage collector way less aggressive. It explains why you didn't have this issue when testing with the debugger attached. Note that you can achieve the same result by pressing Control + F5 in Visual Studio: it'll start the application without attaching the debugger.

Related

Make a unity game look like it has crashed C#

I want to make my Unity game look like it has crashed (Unresponsive Application Crash, Not a code exception crash).
There probably is some function in the Windows API you can call to emulate this.
I have also seen a game called "Pony Island" do this before, so it certainly is possible. However I don't own a copy nor can I decompile a steam game.
If there is a way to actually hang the program while still being able to bring it back at anytime that solution is preferable, this seems to be unlikely.
To be clear, I want it to look legitimate, so I would prefer the windows API be used to change the window color and generate a pop-up, instead of having them in unity as GUI objects or something similar. I also don't really care about cross-compatibility because the Mac API appears to be hard to implement and even harder to test (on a Windows machine), and most likely won't be compatible with as many hacky features as the Windows API is.
Best way to do this safely would be to run some script setting time.timeScale = 0 - effectively 'freezing' the game, while simultaneously playing the windows 'error' sound effect.
(Note: You may have to also pause audio sources and particle emitters from this script, I've not used timescale before an am unsure if it affects these)
I know you suggested against using UGUI but an image with no source placed over the entire screen, with it's colour and alpha tweaked could very easily emulate the 'frozen screen' too.
You could also look into ways to forcibly 'restore'/change fullscreen mode of the window (if it is played in full screen)
I would try to achieve that by using Thread.Sleep(int)
so while in the main thread, i would call that to freeze the entire unity loop for an amount of seconds eg 5 seconds = 5000ms
and check whether you want to continue the crash or not. for example, but not tested, (i don't have unity at my office environment)
Be carefull with this, as this will freeze it for real, you can't do any operation while it still freezing.
public class Crasher : MonoBehaviour
{
public bool isCrash = false;
//The crash in seconds
public float crashDuration = 5;
void Update ()
{
if (isCrash)
{
//Freeze the applicaion for amount of milliSeconds
System.Threading.Thread.Sleep(crashDuration * 1000);
}
}
}

How to detect BLE beacons on Unity3D HoloLens app?

I have built an app in Unity3D which should be able to detect Bluetooth Low-Energy beacons on the Microsoft HoloLens. Here is the Unity C# script code that I used to get this done.
using UnityEngine;
using Windows.Devices.Bluetooth.Advertisement;
public class BeaconDetector : MonoBehaviour
{
private BluetoothLEAdvertisementWatcher _watcher;
void Start()
{
_watcher = new BluetoothLEAdvertisementWatcher();
_watcher.Received += WatcherOnReceived;
_watcher.Start();
}
//This method should be called when a beacon is detected
void WatcherOnReceived(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs args)
{
//Just a simple check if this method is even called
Debug.Log("Beacon detected!");
}
}
The app builds and runs on the HoloLens nicely, but (even after waiting a couple of minutes) I do not get the desired output line in my debug log. This means to me that the WatcherOnReceived() method is never called, which ultimately means that no beacon is detected.
I use some Sensoro SmartBeacon-4AA's which can transmit both iBeacon and Eddystone signals.
I have been trying this for a couple of weeks right now, did several tutorials along the way but I still can not figure out why this is not working for me.
It was a permission problem after all. It is possible to solve this issue in both Unity (pre-build) and Visual Studio (post-build). Here are both solutions:
Solution A: in Unity
Head to Edit > Project Settings > Player.
In the Inspector, open up the tab Publishing Settings.
Under the Capabilities section, make sure that Bluetooth is enabled.
Click on the .gif to expand
Solution B: in Visual Studio (2017)
In your Solution Explorer (Ctrl+Alt+L), expand your project.
Double-click the Package.appxmanifest.
Go to the Capabilities tab.
Again, make sure that Bluetooth is enabled.
Click on the .gif to expand
This will give your app the right to use Bluetooth on the HoloLens.

Shortcut to "Scan new hardware" on Windows?

My computer suffers from the dreaded no sound upon wake-up from sleep (on my HDMI connection) on Windows 10 using the Integrated graphics, Intel HD Graphics 530. I don't know the exact reason for why this is happening, but I understand it as the handshake between monitor and computer is not properly established after wakeup, and thus the audio device is not recognized.
This is confirmed by viewing the available sound devices in Windows.
Apparently this is a common problem, and I tried the following solutions:
Pin-19 trick: Which consist of blocking pin 19, which prevents detection of when monitor goes to sleep. This did not work for me, and I got just a blank screen.
EDID trick: Which involves passing the missing information always on-demand so it doesn't have to try to get the data from the handshake.
Neither solution worked, and the only consistent thing I found working was going to Device Manager, and right clicking the computer, and choosing "Scan for hardware changes".
Is there a way to replicate that with a Windows shortcut on the desktop?
Perhaps a tiny C# program that gets executed every time it wakes up from sleep? Anyone with some Windows programming skills know how to do this?
It's possible to subscribe to an event that's fired when the computer is resuming from sleep.
SystemEvents.PowerModeChanged += OnPowerChange;
Inside the event you can check for the PowerMode and run code depending on which one it is. Resume is the one that tells you the computer is waking up from sleep.
private void OnPowerChange(object s, PowerModeChangedEventArgs e)
{
switch ( e.Mode )
{
case PowerModes.Resume:
ScanForHardwareChanges(); // Your own method
break;
// Possibly hand other power modes too
}
}
Regarding your question about running the hardware scan programmatically, here's a thread that has multiple examples and links that'll help you:
Is there an API call to start a scan for hardware devices?

Windows Phone 8 - 2 Background Audios Clash and both of the App terminates

around a week ago, I submitted an online Background Radio Streaming app for the Windows Phone store. The app was quite good (as I used the Emulator to test it, it was good on all the possible sectors) but when I submitted it for certification, it failed.
According the the error log, if someone is already playing a Music from Music + Video hub and then tries to open this app, both of the apps Crash and stop unexpectedly.
So far I understood, it is because the Music of Music + Video hub is also Background Music and for playing 2 Background Musics at the same time, the apps are Crashing. It can be some other reason but the described one seemed more logical to me.
So, is there anyone who can tell me how to change the state of the app of Music + Video hub? I want to pause or stop the app of Music + Video hub for the time being so that both of the states of the app are not same. In that way, the apps won't clash with each other in the background.
Can anyone help me in this regard?
Use gameHasControl to check for other BAP using music:
bool gameHasControl = Microsoft.Xna.Framework.Media.MediaPlayer.GameHasControl;
if (!gameHasControl)
{
MessageBox.Show("stopping other player"); // normally you should ask if to do that
BackgroundAudioPlayer.Instance.Stop();
}
Once it is Stopped, when you start your BAP, then old instance invokes Shutdown(), and your BAP will be new Instance, which you can normally use. The same is when your BAP is in memory and you start to play from Music+Video Hub.
Only watch out, because when you use XNA, you sometimes need to do:
FrameworkDispatcher.Update();
Otherwise your App will sometimes crash. Good luck.
EDIT - after comment
To make it work you need to add a reference to Microsoft.Phone.BackgroundAudio or use like this:
Microsoft.Phone.BackgroundAudio.BackgroundAudioPlayer.Instance.Stop();
BackgroundAudioPlayer is a Singleton which you are allowed to use - in this case - Stop it playing (of course give the choice to the User).

w8 metro live tile wont animate after computer restart

I have a windows 8 metro app that displays data on a live tile which is refreshed every minute.
When the metro app is started it creates a sequence to do the tile updates. This works perfectly.
The problem:
When I restart my computer the metro tile stops working. Instead it goes back to the default metro tile (app name bottom left image middle).
I can get it to work again by simply starting and stopping the metro app. But I do not wish to do this.
I implement a class that implements IBackgroundTask and implements the run method.
public void Run(IBackgroundTaskInstance taskInstance){
BackgroundTaskDeferral deferral = taskInstance.GetDeferral();
TileScheduler.CreateSchedule();
deferral.Complete();
}
In the metro app package manifest added declaration "Background Task" and under entry point pointed to this class. I also register timer and system event.
This class code basically calls the same code path the main app does when setting the tile sequence for the first time except that it is wrapped with a deferral.
The Question
Is this the right path (as it doesn't seem to be working so I guess my implementation is wrong)? or is there a better way to do this?
This might just be a case of "you can't do that with a simulated program". I'm assuming you are doing this by running the app using a developers license in visual studio. My understanding of how the tiles updating works (correct me if I'm wrong) but the tiles poll a website to get the next item to display. Since you've bounced your box any visual studio spun up services like an ASP.net host etc will not be running so the tile won't be able to get its new update.
If you want to test the functionality before deploying to the store I'd suggest in your project deploying your web service to IIS not to the test environment and configuring IIS to host that service at startup.

Categories