ACTIVATE/DEACTIVATE events don't work for a mobile game app using starling framework - air

So I'm developping a mobile game using the framework starling, and I want the game to pause when I hit the home/back button on my phone, and of course to resume when going back to the game. I did some research and I tried the following:
this.addEventListener(FlashEvent.DEACTIVATE, stopGame);
this.addEventListener(FlashEvent.ACTIVATE, continueGame);
private function continueGame(event:FlashEvent):void
{
...
}
private function stopGame(event:FlashEvent):void
{
...
}
I had to add a new class called FlashEvent that extends flash.events.Event, because I use starling Event and flash Event in the same class, and when I use flash.events.Event I get this error:
Error: Access of undefined property flash
And the same thing for starling.events.Event.
So I used the code above and tried it out in my phone, but when I hit back/home, the game keeps going and the music keeps playing.
My question is: what is the correct way to dispatch the activate/deactivate event in an air mobile app?

Used in your main startup class.
(note that in this example 'app:Main' is the class I call the Starling start method.
Note that you should determine event classes with:
starling.events.Event.XXX
flash.events.Event.XXX
_mStarling.addEventListener(starling.events.Event.ROOT_CREATED,
function onRootCreated(event:Object, app:Main):void
{
_mStarling.removeEventListener(starling.events.Event.ROOT_CREATED, onRootCreated);
app.start(assets);
_mStarling.start();
NativeApplication.nativeApplication.addEventListener(
flash.events.Event.ACTIVATE, function (e:*):void {
_mStarling.start();
try {
// optionally call some other methods
} catch(e:Error) {
}
});
NativeApplication.nativeApplication.addEventListener(
flash.events.Event.DEACTIVATE, function (e:*):void {
try{
// optionally call some other methods before stopping
} catch(e:Error) {
}
_mStarling.stop();
});
});

My code
public function Main()
{
stage.addEventListener(flash.events.Event.DEACTIVATE, onDeactivate);
stage.addEventListener(flash.events.Event.ACTIVATE, onActivate);
}
And you set a paused boolean and check for it at the top of your game loop:
if ( paused ) return;
If you have animations you use a juggler and if you aren't calling advanceTime on the juggler it is paused.

Related

Notifying main thread object when background operation finishes in kotlin native

I'm building an iOS app using kotlin native and having problems with inter-thread communication.
In my app there is a class that makes an http request in a background thread (using coroutines) and needs to update the parent class state when the operation finishes. Something like this:
class Feed {
var items
fn update() {
asyncHttpRequest("http://myservice.com") { newItems ->
CoroutineScope(Dispatchers.Main).launch {
items = newItems
}
}
}
}
This fails because the feed object is frozen when passed as part of the lambda function context so it cannot be updated with the new items when the http background operation finishes.
What is the best way to design and implement something like this in kotlin-native?
Thank you!
One option would be to use atomics for modifying state concurrently:
AtomicReference
touchlab/Stately

MvvmCross and back button in Windows Phone app

I'm building a Windows Phone app (8.1 using WinRT) using MvvmCross. To navigate to a new view I using ShowViewModel(). But when I hit the back button on the phone the app is closing instead of navigating back to the first view. How can I do it I want to return to the first view when I hitting the back button?
I solved it to use a interface in my viewmodel with a backbutton event, then I wrote a client speific implementation of it. In the viewmodel I handle the event and called the close method in the my base class MvxViewModel. Read more about my solution on my blog, http://danielhindrikes.se/windows-phone/handle-windows-phone-back-button-pressed-when-using-mvvm/
Here's a simpler solution. Create a base type for all your WP pages that derives from MvxWindowsPage. Then, handle the back key there and route the proper information to your VM:
public abstract class MyBaseView : MvxWindowsPage {
public MyBaseView() {
this.InitializeComponent();
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e) {
if (Frame.CanGoBack) {
var vm = ViewModel as MyBaseViewModel;
if (vm != null) {
e.Handled = true;
vm.GoBackCommand.Execute(null);
}
}
}
}
Now, you also have to make sure that you have a base viewmodel which derives from MvxViewModel and from which you derive all your VMs. That base VM should have a GoBackCommand observable property, and executing that command should do a simple Close(this).
To see what's going on under the hood, see this related question: Windows Phone 8.1 Universal App terminates on navigating back from second page?
EDIT
Fixed declaration.

Metro c++ async programming and UI updating. My technique?

The problem: I'm crashing when I want to render my incoming data which was retrieved asynchronously.
The app starts and displays some dialog boxes using XAML. Once the user fills in their data and clicks the login button, the XAML class has in instance of a worker class that does the HTTP stuff for me (asynchronously using IXMLHTTPRequest2). When the app has successfully logged in to the web server, my .then() block fires and I make a callback to my main xaml class to do some rendering of the assets.
I am always getting crashes in the delegate though (the main XAML class), which leads me to believe that I cannot use this approach (pure virtual class and callbacks) to update my UI. I think I am inadvertently trying to do something illegal from an incorrect thread which is a byproduct of the async calls.
Is there a better or different way that I should be notifying the main XAML class that it is time for it to update it's UI? I am coming from an iOS world where I could use NotificationCenter.
Now, I saw that Microsoft has it's own Delegate type of thing here: http://msdn.microsoft.com/en-us/library/windows/apps/hh755798.aspx
Do you think that if I used this approach instead of my own callbacks that it would no longer crash?
Let me know if you need more clarification or what not.
Here is the jist of the code:
public interface class ISmileServiceEvents
{
public: // required methods
virtual void UpdateUI(bool isValid) abstract;
};
// In main XAML.cpp which inherits from an ISmileServiceEvents
void buttonClick(...){
_myUser->LoginAndGetAssets(txtEmail->Text, txtPass->Password);
}
void UpdateUI(String^ data) // implements ISmileServiceEvents
{
// This is where I would render my assets if I could.
// Cannot legally do much here. Always crashes.
// Follow the rest of the code to get here.
}
// In MyUser.cpp
void LoginAndGetAssets(String^ email, String^ password){
Uri^ uri = ref new URI(MY_SERVER + "login.json");
String^ inJSON = "some json input data here"; // serialized email and password with other data
// make the HTTP request to login, then notify XAML that it has data to render.
_myService->HTTPPostAsync(uri, json).then([](String^ outputJson){
String^ assets = MyParser::Parse(outputJSON);
// The Login has returned and we have our json output data
if(_delegate)
{
_delegate->UpdateUI(assets);
}
});
}
// In MyService.cpp
task<String^> MyService::HTTPPostAsync(Uri^ uri, String^ json)
{
return _httpRequest.PostAsync(uri,
json->Data(),
_cancellationTokenSource.get_token()).then([this](task<std::wstring> response)
{
try
{
if(_httpRequest.GetStatusCode() != 200) SM_LOG_WARNING("Status code=", _httpRequest.GetStatusCode());
String^ j = ref new String(response.get().c_str());
return j;
}
catch (Exception^ ex) .......;
return ref new String(L"");
}, task_continuation_context::use_current());
}
Edit: BTW, the error I get when I go to update the UI is:
"An invalid parameter was passed to a function that considers invalid parameters fatal."
In this case I am just trying to execute in my callback is
txtBox->Text = data;
It appears you are updating the UI thread from the wrong context. You can use task_continuation_context::use_arbitrary() to allow you to update the UI. See the "Controlling the Execution Thread" example in this document (the discussion of marshaling is at the bottom).
So, it turns out that when you have a continuation, if you don't specify a context after the lambda function, that it defaults to use_arbitrary(). This is in contradiction to what I learned in an MS video.
However by adding use_currrent() to all of the .then blocks that have anything to do with the GUI, my error goes away and everything is able to render properly.
My GUI calls a service which generates some tasks and then calls to an HTTP class that does asynchronous stuff too. Way back in the HTTP classes I use use_arbitrary() so that it can run on secondary threads. This works fine. Just be sure to use use_current() on anything that has to do with the GUI.
Now that you have my answer, if you look at the original code you will see that it already contains use_current(). This is true, but I left out a wrapping function for simplicity of the example. That is where I needed to add use_current().

Simple example of DispatcherHelper

I'm trying to figure out how can I use DispatcherHelperftom MVVM light toolkit in SL, but I can't find any example.
From home page of this framework I know that
DispatcherHelper class, a lightweight class helping you to create
multithreaded applications.
But I don't know how to use it.
How and for what I can use it?
You only need the DispatcherHelper when yo want to make changes to components on your UI thread, from code that runs on a different thread. E.g. in an Silverlight application you call a web service to retrieve some data asynchroneously, and now want to inform the Ui that the data is present via a OnNotifyPropertyChanged event.
First you have to initialize the DispatcherHelper. In Silverlight you do this in Application_Startup:
//initialize Dispatch helper
private void Application_Startup( object sender, StartupEventArgs e) {
RootVisual = new MainPage();
DispatcherHelper.Initialize();
}
In WPF the initialization is done in the static constructor of you App class:
static App() {
DispatcherHelper.Initialize();
}
Then in your event, handling the completion of your asnc call, use the following code to call RaisePropertyChanged on the UI thread:
DispatcherHelper.CheckBeginInvokeOnUI(
() => RaisePropertyChanged(PowerStatePropertyName)
);
DispatcherHelper.BeginInvokeOnUl expects an Action so you can use any code in here just use
DispatcherHelper.CheckBeginInvokeOnUI(
() => { /* complex code goes in here */ }
);
to do more complex tasks.

Monotouch: UIAlertView and WCF services, debugger.StackTrace

I'm currently using WCF in monotouch to call an existing service and a custom UIAlertView.
The problem is that if I create an UIAlertView as class instance and the I do the following:
public override void ViewDidAppear()
{
_alertView.Message = "Loading...";
_alertView.Show();
_client.GetDataAsync("test");
_client.GetDataCompleted += GetDataCompletedDelegate;
base.ViewDidAppear();
}
void GetDataCompletedDelegate(object sender, GetDataEventArgs)
{
// do someting with data
_alertView.Hide();
}
it works but this advice is written in console : UIAlertView: wait_fences: failed to receive reply: 10004003
else, if I try to run this code:
public override void ViewDidAppear()
{
using(CustomAV _alertView = new CustomAV())
{
_alertView.Message = "Loading...";
_alertView.Show();
_client.GetDataAsync("test");
_client.GetDataCompleted += delegate{
InvokeOnMainThread(delegate{
// do someting with data
_alertView.Hide();
});
};
}
base.ViewDidAppear();
}
the first time the code run, but now alert is shown. The second time the simulator can't startup. Couldn't register "com.yourcompany.wcftest" with the bootstrap server. Error: unknown error code. This generally means that another instance of this process was already running or is hung in the debugger.StackTrace. In this case I have to reboot the machine.
Thank you in advance.
EDIT:
Thank you Geoff, I've checked my code and into GetDataCompletedDelegate I've inserted a function that runs inside the UI Thread.
InvokeOnMainThread(delegate{
doSomething();
});
private void doSomething()
{
// do stuff here
_alertView.Hide();
}
The fency error continues to appear. If I use your solution inside doSomething() method, it works
_alertView.InvokeOnMainThread(delegate{
_alertView.Hide();
});
Why? Maybe I didn't understand, but in the first snippet of code do something() works in the UI thread!! Isn't true?
You have 2 seperate problems here.
1: _alertView.Hide () is not running on the UI thread (this is what causes the fences error)
2: In your second example you're disposing the UIAlertVeiw immediately after creating it, but you have a instance delegate dangled off it. This crashes the runtime in a hard way, and then when you run it again since the old crashed process is still running the simulator wont let you start a second instance.
Use case #1 but do _alterView.InvokeOnMainThread (delegate { _alertView.Hide (); });