User consent to stop the playing audio - windows-phone-7

Windows Phone 7.5 / Silverlight app
If user is playing music / radio on their phone and they try to launch my application, I want to give user an option to stop the currently playing option.
Working fine:
The message popup shows up fine. When I select Cancel, the popup closes, the music keeps playing and my app starts/works as normal.
Issue:
If I select Ok i.e. to stop the currently playing music on phone, the music stops but at the same time my app also exits.
Any ideas what I am doing wrong here?
Here is the code I am using. I call this method on launching:
private void CheckAudio()
{
if (FMRadio.Instance.PowerMode == RadioPowerMode.On)
{
MessageBoxResult Choice;
Choice = MessageBox.Show("For better user experience with this application it is recommended you stop other audio applications. Do you want to stop the radio?", "Radio is currently playing!", MessageBoxButton.OKCancel);
if (Choice == MessageBoxResult.OK)
{
FMRadio.Instance.PowerMode = RadioPowerMode.Off;
}
}
if (MediaPlayer.State == MediaState.Playing)
{
MessageBoxResult Choice;
Choice = MessageBox.Show("For better user experience with this application it is recommended you stop other audio/video applications. Do you want to stop the MediaPlayer?", "MediaPlayer is currently playing!", MessageBoxButton.OKCancel);
if (Choice == MessageBoxResult.OK)
{
MediaPlayer.Stop();
}
}
}
Update:
I posted my solution below. Do let me know if I am doing anything wrong.

I found the following error was being thrown:
FrameworkDispatcher.Update has not been called. Regular
FrameworkDispatcher. Update calls are necessary for fire and forget
sound effects and framework events to function correctly.
So I added this code and now it is working fine. Now upon clicking OK, the music player stops and my app launches fine. I call the SetupTimer method from InitializeComponent in App.xaml.cs
private GameTimer gameTimer;
private void SetupTimer()
{
gameTimer = new GameTimer();
gameTimer.UpdateInterval = TimeSpan.FromMilliseconds(33);
// Call FrameworkDispatcher.Update to update the XNA Framework internals.
gameTimer.Update += new EventHandler<GameTimerEventArgs>(gameTimer_Update); //delegate { try { FrameworkDispatcher.Update(); } catch { } };
// Start the GameTimer running.
gameTimer.Start();
// Prime the pump or we'll get an exception.
FrameworkDispatcher.Update();
}
void gameTimer_Update(object sender, GameTimerEventArgs e)
{
try { FrameworkDispatcher.Update(); }
catch { }
}
If anybody sees any problem/issue with the above please do let me know. Thanks.

Related

How to Poll For Controller Input In UWP App

I'm unsure about the best practice for obtaining and updating input received from a controller monitored using the GamePad class in UWP.
I've seen a couple of examples of people using Dispatch Timers and async loops inside the GamePadAdded event. In Win32 applications, I would have handled input in the WinMain update/message loop, but in UWP apps I don't know of anything similar.
Is there a loop in UWP apps that input should be collected/handled like in Win32 apps? What is the recommended protocol for polling for input from a input device (nominally a Xbox One controller)?
I'm happy to read more about UWP app development but I'm unsure of any guides that reference something like this.
Edit: It would be productive if, instead of downvoting and moving on, you shared thoughts on why this question deserved a downvote.
I've seen a couple of examples of people using Dispatch Timers and async loops inside the GamePadAdded event
This is the right way in UWP app to read Gamepad data. A little suggestion is, move the loop reading part on UI thread if you need to update UI frequently. See the solution in this blog
Is there a loop in UWP apps that input should be collected/handled like in Win32 apps
You may make a wrapper with custom event, see the open source implementation: XBoxGamepad
public class XBoxGamepad
{
private List<Gamepad> _controllers = new List<Gamepad>();
private bool _running = true;
Task backgroundWorkTask;
public event EventHandler<GamepadButtons> OnXBoxGamepadButtonPressA;
//omitted......
public XBoxGamepad()
{
Gamepad.GamepadAdded += Gamepad_GamepadAdded;
Gamepad.GamepadRemoved += Gamepad_GamepadRemoved;
backgroundWorkTask = Task.Run(() => PollGamepad());
}
//omitted......
private void Start()
{
_running = true;
}
public void Stop()
{
_running = false;
}
public async Task PollGamepad()
{
while (true)
{
if (_running)
{
foreach (Gamepad controller in _controllers)
{
if (controller.GetCurrentReading().Buttons == GamepadButtons.A)
{
OnXBoxGamepadButtonPressA(controller, controller.GetCurrentReading().Buttons);
}
//omitted......
}
}
await Task.Delay(50);
}
}
private void Gamepad_GamepadRemoved(object sender, Gamepad e)
{
_controllers.Remove(e);
}
private void Gamepad_GamepadAdded(object sender, Gamepad e)
{
_controllers.Add(e);
}
}

How can I correctly close an application in Application_Launching event

I want to close my app if network not available.
I check network in App.cs:
private void Application_Launching(object sender, LaunchingEventArgs e)
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
//close my app
}
else
{
//continue to work
}
}
Is there a better way to do it?
Thanks in advance.
just add reference to Microsoft.Xna.Framework.Game i'm sure you can achieve exit with this code and it will be ok. if you wanna show message box you have to do it in main page
what i would do:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (!NetworkInterface.GetIsNetworkAvailable())
{
MessageBoxResult m = MessageBox.Show(Sorry, no internet connection is available.do you want to exit the application , "Oops...", MessageBoxButton.OKCancel);
if (m == MessageBoxResult.OK)
{
var g = new Microsoft.Xna.Framework.Game();
g.Exit();
}
}
}
you should provide a "gentle" way for closing
5.1.2 - App closure
The app must handle exceptions raised by the any of the managed or native System API
and not close unexpectedly. During the certification process, the app is monitored
for unexpected closure. An app that closes unexpectedly fails certification. The app
must continue to run and remain responsive to user input after the exception is
handled.
for more information visit this link
Application.Current.Terminate();

how to disable location services in my WP7 app

I'm making a windows phone app which displays where the closest campus shuttles are (among other things). Windows Phone requires apps to allow the users to turn off location services within the app.
So, I added a toggle for it on a settings page, but it doesn't seem to do anything.
Here's the viewmodel where I declared the geocoordinatewatcher.
public MainViewModel()
{
geoWatcher = new GeoCoordinateWatcher();
if (geoWatcher.TryStart(false, TimeSpan.FromSeconds(30) )==false )
{ MessageBox.Show("The location services are disabled for this app. We can't detect the nearby stops. To turn location services back on, go to the settings page.", "Warning", MessageBoxButton.OK); }
}
private GeoCoordinateWatcher geoWatcher;
public GeoCoordinateWatcher GeoWatcher
{
get
{
return geoWatcher;
}
set
{
if (geoWatcher != value)
{
geoWatcher = value;
NotifyPropertyChanged("GeoWatcher");
}
if(geoWatcher.Status== GeoPositionStatus.Disabled)
{
geoWatcher.Stop();
}
}
}
and here's the bulk of the settings page
public SettingsPage()
{
InitializeComponent();
if (App.ViewModel.GeoWatcher.Status == GeoPositionStatus.Ready)
{
locToggle.IsChecked = true;
locToggle.Content = "On";
}
else
{
locToggle.IsChecked = false;
locToggle.Content = "Off";
}
}
private void toggleChecked(object sender, RoutedEventArgs e)
{
locToggle.Content = "On";
App.ViewModel.GeoWatcher.Start();
MessageBox.Show("this is the status " + App.ViewModel.GeoWatcher.Status.ToString(), "Info", MessageBoxButton.OK); //for debugging
}
private void toggleUnchecked(object sender, RoutedEventArgs e)
{
locToggle.Content = "Off";
App.ViewModel.GeoWatcher.Stop();
MessageBox.Show("this is the status " + App.ViewModel.GeoWatcher.Status.ToString(), "Info", MessageBoxButton.OK); //for debugging
}
When i turn the toggle off and click away from the Settings page, and go back to it, the toggle is re-enabled again.
I tried putting in a message box on the functions to debug but the status always says "Ready" and my app still uses the location services, even when I turn the toggle to "off".
Is there something I should be adding to the code so that the toggle will properly make my app stop using location services across my app if it's disabled on the settings page? Or should I be checking something else besides GeoPositionStatus? I couldn't figure out a way to make my app actually change the location services permissions or PositionStatus.
I looked at this page here, but am still confused since I followed the example at the bottom of the page, to no avail. I searched StackOverflow but I couldn't seem to find a similar question with WP. I also posted this on the AppHub forums though.
Thanks!
In your MainViewModel you need to check if they have allowed location services before you use the geocoordinatewatcher.
if(settings.LocationAllowed)
{all your code for using location}
You should probably take into account a few factors/points, most of which, you have. Anyway, you might find these helpful.
Your application settings toggle should only show when the location service is switched on on the device
GeoPositionStatus is just an Enum which contains the types of statuses.
StatusChanged is the event which is to be handled to check for changes in the device settings. See this.
You cannot change the device settings from the application.
Add event handlers before you call start on the watcher.

WP7 Navigation - NullReferenceException

I need to navigate to a certain page the first time my app is run, to gather login details etc. I'm using IsloatedStorageSettings to save a value to determine if this is the first run of the app or not, which works fine.
My problem is actually navigating to my 'first run' page when the app is run for the first time, using NavigationService, it seems NavigationService is not created at this point so is still null. When is NavigationService created or how can I work around this?
My code (in the constructor of my main page:
if ((bool)settings["firstRun"])
{
if (NavigationService != null)
{
NavigationService.Navigate(new Uri("/FirstRun.xaml", UriKind.Relative));
}
else
{
MessageBox.Show("Navigation service must be null?"); //always prompts
}
}
else
{
InitializeComponent();
}
Peter Torr has a great blog post on the ins and outs of redirecting for the initial navigation, though for user login I'd suggest that you either use a full screen popup or have a login control on your "normal" start page and toggle visibility based on your first run condition.
Add in class
private bool m_onNavigatedToCalled = false;
In ctor
this.LayoutUpdated += new EventHandler(MainPage_LayoutUpdated);
Then in code
void MainPage_LayoutUpdated(object sender, EventArgs e)
{
if (m_onNavigatedToCalled)
{
m_onNavigatedToCalled = false;
Dispatcher.BeginInvoke(() =>
{
if (NavigationService != null)
{
MessageBox.Show("Navigation not null?"); //always prompts
}
else
{
MessageBox.Show("Navigation service must be null?");
}
//StartApp(); do all stuff here to keep the ctor lightweight
}
);
}
}

SAPI and Windows 7 Problem

I'm trying to recognize speech with Windows 7 but it always recognizes a speech as a command or just says "What was that?".
How I can get all speeches?
CODE:
SpeechRecognizer _speechRecognizer;
public Window1()
{
InitializeComponent();
// set up the recognizer
_speechRecognizer = new SpeechRecognizer();
_speechRecognizer.Enabled = false;
_speechRecognizer.SpeechRecognized +=
new EventHandler<SpeechRecognizedEventArgs>(_speechRecognizer_SpeechRecognized); }
Perhaps you want to use the .net System.Speech namespace instead of SAPI? There is a very good article that was published a few years ago at http://msdn.microsoft.com/en-us/magazine/cc163663.aspx. It is probably the best introductory article I’ve found so far. It is a little out of date, but very helfpul. (The AppendResultKeyValue method was dropped after the beta.)
Are you trying to use a shared recognizer? That may be why you are seeing commands. Do you have a specific task for recognition? In that case, you would be better served with a task specific grammar and an inproc recognizer.
If you need to handle any words, use the DictationGrammar that comes with System.Speech. See http://msdn.microsoft.com/en-us/library/system.speech.recognition.dictationgrammar%28VS.85%29.aspx
For fun, I whipped together the simplest .NET windows forms app to use a dictation grammar that I could think of. I created a form. Dropped a button on it and made the button big. Added a reference to System.Speech and the line:
using System.Speech.Recognition;
Then I added the following event handler to button1:
private void button1_Click(object sender, EventArgs e)
{
SpeechRecognitionEngine recognizer = new SpeechRecognitionEngine();
Grammar dictationGrammar = new DictationGrammar();
recognizer.LoadGrammar(dictationGrammar);
try
{
button1.Text = "Speak Now";
recognizer.SetInputToDefaultAudioDevice();
RecognitionResult result = recognizer.Recognize();
button1.Text = result.Text;
}
catch (InvalidOperationException exception)
{
button1.Text = String.Format("Could not recognize input from default aduio device. Is a microphone or sound card available?\r\n{0} - {1}.", exception.Source, exception.Message);
}
finally
{
recognizer.UnloadAllGrammars();
}
}

Resources