Close Application on START Button (Windows Phone 7) - c#

I want my application to be terminated after the "Start" button is clicked on windows phone, I do not know which event is fired by the Start button or how I can override it, thanks!

Try this once -:
PhoneApplicationService.Current.State["isstartnav"] = true;
Verify the above condition and call the below specified method:
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
This Method will remove the stack entries from the RAM and your app will be removed from the memory.

The answer is, you can't. Only the user and the OS can close an app. Windows Phone 8 has an Application.Terminate() method, but with Windows Phone 7, you cannot do any such thing.
One hack is to throw some exception in your Application.Deactivated event. Doing so will result in an app crash and eventually close your app, but your app will fail certification at Windows Phone Store.

Related

How prelaunch works?

Looking for some feature that can make my app start up even fast, I found the prelaunch feature in the Microsoft documentation that would help open the app faster. But even if I register the app to enable prelaunch, the OnLaunched event keeps getting false in e.PrelaunchActivated.
(I only could test this feature using the VS option 'Debug UWP Prelaunch' in debug mode).
Do I need a Microsoft certificate to use it?
How long does the OS take to understand that my app is eligible to prelaunch?
Does this influence the fact that I'm getting false at the event?
I made a test and the prelaunch works correctly. I'll post my code here and explain how the prelaunch works. Hope it will help you solve your question.
Here is the sample code that I used:
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
bool canEnablePrelaunch = Windows.Foundation.Metadata.ApiInformation.IsMethodPresent("Windows.ApplicationModel.Core.CoreApplication", "EnablePrelaunch");
// ********
// some other code here
// *********
//check if it is prelaunched
if (e.PrelaunchActivated == false)
{
// On Windows 10 version 1607 or later, this code signals that this app wants to participate in prelaunch
if (canEnablePrelaunch)
{
TryEnablePrelaunch();
}
// ******
// normal code
// ******
}
else
{
//prelaunched
// do some logic that don't require UI thread.
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), "PreLaunched");
}
// Ensure the current window is active
Window.Current.Activate();
}
}
As you could see, I add an else sentence to do the work when the app is prelaunched.
When testing via the Debug Universal Windows App Prelaunch mode in Visual Studio, the whole process should be like:
Choose the Debug Universal Windows App Prelaunch mode, then the app will be prelaunched.
The OnLaunched event will be fired and you will go into the else sentence because it is prelaunched.
You could do your work in the OnLaunched event for prelaunched
Then the app will go to suspend status.
Now, the user launches the app from Start Menu.
The OnLaunched event will be fired again and this time it will show e.PrelaunchActivated == false because it is launched by the user, it is not prelaunched. I suspect this is the behavior that you are getting.
So this is the whole process about how the prelaunch works. This is also mentioned here: App launch.
In my case, Windows does not use Prelaunch when app is deployed by Visual Studio, but after installing it from the Store it works as expected. User must run an app at least one time and next time you will see it in the Task Manager. Will it work or not, depends on the amount of available memory, but I found it working even on a device with 4Gb of RAM.

Using UWP Geolocation-API with Win32-Application on Windows 10

We're building a multi-platform (desktop- and tablet-computers) application targeting Windows 8.1 as well as 10. As we process spatial data, we offer the user the possibility to use his current location using the device's gps receiver. To allow easy adaption to the (hardware) environment, we placed the gps-logic (including the API-calls) into an external assembly that we load based on a configuration.
Recently we discovered some problems with the gps-module using the Geolocator from Windows.Devices.Geolocation-API under windows 10 (but previously running without problem on Windows 8.1), not delivering any location. Further investigation and RTFM showed up, that - under Windows 10 - we were obliged to call the RequestAccessAsync before calling for the location.
As the RequestAcessAsync-method isn't available in Windows 8.1, we decided to create a new assembly, targeting Windows 10 (and then easily being bound/used through our configuration), what worked quite well:
public Win10GpsProvider()
{
RequestAccessAsync();
}
public async void RequestAccessAsnyc()
{
//next line causes exception:
var request = await Geolocator.RequestAccessAsync();
switch (request)
{
// we don't even get here... :(
}
}
Only up to running into an exception that gets thrown as soon as the RequestAccessAsync-method is being called (in UI-thread), stating that the call has to be made in the context of an app container.
This operation is only valid in the context of an app container. (Exception from HRESULT: 0x8007109A)
The exception occurs on both, desktop as well as tablet (verified through remoted debugging).
Searching a bit more, adding the "location" as a required capability to the package.appxmanifest may help:
<Capabilities>
<Capability Name="location"/>
</Capabilities>
That's where we're actually stuck at the moment:
We don't have an UWP-application (and actually don't want/can change that, as we're targeting Win 8.1 as well and have a defined deployment workflow including setups)
We can't get the assembly run without exception as there is no UWP app/context
Is there a way to get a separate assembly that targets the Windows 10 version of the Windows.Devices.Geolocation-API and can be called/loaded by a Win32-application?
AFAIK, it is not doable to call RequestAcessAsync method and make it work in Windows 8.1 app.
But if you directly use Geoposition in windows 8.1 project, and run this windows 8.1 app on windows 10 device for example on desktop, the permission request dialog will also be displayed:
So there should be no problem if you don't call RequestAcessAsync method in windows 8.1 app.
But in case user choose "No" in this permission request dialog, we can catch the exception and launch the Setting page to force user to enable the Location setting for this app for example like this:
private Geolocator _geolocator = null;
private uint _desireAccuracyInMetersValue = 0;
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
var _cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
_geolocator = new Geolocator { DesiredAccuracyInMeters = _desireAccuracyInMetersValue };
Geoposition pos = await _geolocator.GetGeopositionAsync().AsTask(token);
// Subscribe to PositionChanged event to get updated tracking positions
_geolocator.PositionChanged += OnPositionChanged;
// Subscribe to StatusChanged event to get updates of location status changes
_geolocator.StatusChanged += OnStatusChanged;
}
catch (Exception ex)
{
await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
}
}
This code in windows 8.1 project works fine both on windows 8.1 device and windows 10 device. And I don't quite understand what is your Win32-application for here?

Application.Current.Exit in Windows Phone 8.1 doesn't terminate app

How should I "properly" programmatically terminate a Windows Phone 8.1 app?
Application.Current.Exit (); doesn't work. My code continues right through it.
Here's the snippet:
public static async Task ShowAndGo (String MessCode, String MessText, Boolean Xit)
{
String Mess = ""; // Start out with an empty Message to tell Joe User.
String Title = ""; // And an empty title too.
MessageDialog messageDialog = new MessageDialog (Mess, Title);
await messageDialog.ShowAsync (); // Stop and wait for user to acknowledge.
if (!Xit) // We're done here if we're not goin' down.
return;
//
// If we're goin' down,
// we have a lot of cleanup to do.
//
Application.Current.Exit (); // This should stop us. But it doesn't.
}
How should I "properly" programmatically terminate a Windows Phone 8.1 app?
The short: There isn't a "proper" way, and it's recommend that you shouldn't
The remarks on the Application.Exit method states:
Normally, however, you should not provide this UI because the system automatically manages app lifetime and terminates suspended apps as needed to free resources.
The guidelines say you should:
Design your app to suspend when the user switches away from it and resume when the user switches back to it.
Don't terminate the app when the user navigates away from the app or closes the app using the close button. The operating system ensures that there is a consistent way for the user to access and manage apps. Your app is suspended when it is no longer visible to the user. By leaving the application lifecycle to the system, you ensure that your user can return to your app as efficiently as possible. Doing so also provides the best system performance and battery life from the device.
Rather register an event handler for the Suspending event.
It is called when the app is suspended. You can use this event handler to save relevant application and user data to persistent storage.
It is good to read the Application Lifecycle page.
How to programmatically terminate a Windows Phone 8.1 app?
Windows Phone 8.1
Application.Current.Exit();
Windows Phone 8.1 (Silverlight)
Application.Current.Terminate();
Your code
I used your code as is for testing, and it worked as expected when I remove:
if (!Xit) // We're done here if we're not goin' down.
return;
Xit is never assigned in your code sample; if Xit is false then the termination line will not be reached. Just remember that bool values are false by default (if no value is given to them)
Try using Application.Current.Terminate(); instead of Application.Current.Exit ();
For example
private void Exit_Button(object sender, System.Windows.Input.GestureEventArgs e)
{
Application.Current.Terminate();
}

In windowsphone 8/8.1 Silverlight, is it possible to distinguish, if the app is closed by user or is terminated in background

I have a requirement where in if the windows phone app is terminated in background, i want to show the same page where the user left, when the app is launched again.
However if user closes the app, i have to show the login page.
Is it possible that a windows phone silverlight app terminates in background, due to OS resource requirements, similar to windows tablet apps ? i never saw a windows phone silverlight app getting terminated in background, what i can see that a max of 7-8 recent apps are displayed when we long press on the back button. even if my app is not not there in the recent list it gets resumed to the same page and i get the event IsApplicationInstancePreserved as true.
However there seems to be no way to identify if the app is terminated by OS, so that i can navigate to the same page where user was previously.
There are two ways of closing a windows phone app
1) press the back button on the first page , in this case the closing event is fired.
2) Long press the back button and close your apps in the recent app list, when user does a long press and closes, the deactivated event is fired.
When user presses the windows button the deactivated event is fired and app goes in background.
If your app is terminated/closed in the background then when you launch the app then in the launch method OnLaunchApplicationAsync(LaunchActivatedEventArgs args) args has this property called PreviousExecutionState which is Enum of type ApplicationExecutionState and has the following values:
public enum ApplicationExecutionState
{
NotRunning = 0,
Running = 1,
Suspended = 2,
Terminated = 3,
ClosedByUser = 4,
}
Hope this helps!

Exit(Quit) implementation

In my windows phone7(Silverlight) Application I have to display a message box asking, the user to confirm(Yes/No) before exit from the application [on device back button click].
The problem is I have to use a custom messagebox(using a popup) to get user confirmation, and I have no way to get exit from the application.(No method found which will exit the application like dispose() or close()).
if I didn't have to use a custom messagebox, the on the Device back key press event "OnBackKeyPress" I would have use the following logic and done my work
MessageBoxResult res = MessageBox.Show("Do you want to Exit?", "Exit", MessageBoxButton.OKCancel);
if (res == MessageBoxResult.OK)
{
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
}
else
{
e.Cancel = true;
}
The problem is I need to use the custom messagebox and done this work. Same problem arise if need to implement a button to exit the application with out using the device back button.
I found in several posts suggesting to throw an exception and make this done. Following are some of them
http://mobile.dzone.com/articles/windows-phone-mango-sample-3
http://imaginativeuniversal.com/blog/post/2010/08/22/How-to-Quit-a-WP7-Silverlight-Application.aspx
I don't think that this is a good practice and also not sure if the windows market place will certify this way. Would like to hear the thoughts of once who have experienced this issue, and any suggestion to Achieve this(Terminate the application). Thanks inadvance....!!!!
If you want to submit to the Marketplace you've got a couple of problems because of the following certification requirements:
5.2.4.2 Pressing the Back button from the first screen of an application must close the application.
5.2.2 A Windows Phone application is closed and terminated by the OS when the user navigates away from the application. When an application is started after being closed, its launch time must meet the requirements in Section 5.2.1 – Launch Time
5.2.3 A Windows Phone application is deactivated when the user presses the Start button or if the device timeout causes the lock screen to engage. A Windows Phone application is also deactivated with it invokes a Launcher or Chooser API.
This is a couple instances where you simply can't display a message box.
And technically using an exception to termniate the app is a violation:
5.1.2 The application must handle exceptions raised by the .NET Framework and not close unexpectedly. During the certification process, the application is monitored for unexpected closure. An application that closes unexpectedly fails certification. The application must continue to run and remain responsive to user input after the exception is handled.
As a developer, part of your job is communicating to users about requirements that are unrealistic or unreasonable.
Sorry, no way to do this. Before mango update you could Clear the back stack, then programmatically trigger the Back button. but as of SDK 7.1 (wp7.5) we can no longer do this.
My recommendation is to create a custom Exception type ApplicationXExitException and throw that to exit the app. The reason for the custom type is so that when you pull your exception logs from the marketplace, you'll know the ones that were indeed unintended exceptions crashing the app, vs your exception to intentionally exit the app.
You can hook an event raising after your custom messagebox closes. Event arguments will keep information about user's choice. Depending on that you will decide whether to exit app or not.

Categories

Resources