App freezing after several restarts - codenameone

I built this app that takes pictures, displays them for acceptance and uploads them to a webserver via post.
It is very simple in concept and execution. But then the app is freezing in the Android handset (I have an Xperia Z3+ which i has a fairly good amount of resources, also tried in a Moto X).
To try and reproduce this I take a picture (it will automatically tried the upload)... push the power button for the screen to shutdown... then when I light up the screen it takes a while for the app to start working again (I can see because I have a background animation). After some retries of these... the app will freeze and I'll have to close it to retry.
Any suggestions on how to troubleshoot this problem?
My thinking is that I can aliviate the problem a little by removing the animation elements from the screen... at least the perceived performance will be far better is the app does not appear frozen on any app switch... therefore I want to be able to use the onPause, onStop from the activity lifecycle events to clear the animations. I guess those objects are serialized, so I will save serialization and deserialization time and also the perceived performance will improve as no freezed app will be seen while the onResume, onRestart events.
Is this posible?
Thank you very much
Chuck

This isn't caused by the animation, it may be caused by an uncaught Exception or poor app performance.
To review your app performance, move any long process that requires feedback to the UI (AsyncTask) to postShow() method of your forms and not beforeShow(). If it doesn't require feedback to UI in real time (IntentService), consider using Display.getInstance().scheduleBackgroundTask() which runs your task on a low priority thread while serializing it and this can be done in the beforeShow() method. If your forms are handcoded (Not GUI), do heavy long process in addShowListener().
Also cut down the amount of images you use in your app as this could also hinder your app performance when loading heavy images.
Avoid unnecessary use of revalidate(), usually by not calling it in a loop, it's a bit expensive, use repaint() instead.
You can also use Android ddms to check if your app is running into some errors.
Locking your screen or minimizing shouldn't affect your app in anyway other than when the app is starting up and the splash screen is shown (This usually freezes the app if you minimize your app when splash is shown). I believe this is a known issue though.
Another option could be the "suspend-resume" behavior. When an app is suspended (power button, incoming phone call etc.) the stop() method is invoked followed by a call to the start() method when it returns.
If you have a progress indicator during the stop() method then the restore call will reshow the progress indicator with the previous form as its "before form". That way when the progress indicator is dismissed it shows the "previous form". You can test this behavior in the simulator using the "suspend/resume" menu.
To workaround it just dispose the progress indicator in the stop() method as such:
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}

Related

How to find what freezes Chrome when it runs an AngularJS application?

I'm inspecting a performance issue with an AngularJS application.
When performing specific actions, the CPU usage goes to 100%, the Chrome window freezes, and I have to manually terminate the process using Chrome's task manager.
I tried to debug the app (DevTools' Sources tab), but the application is quite large and the code is minified, which means that finding the issue won't be easy: I see a lot of code triggered by the digest cycle, and can't figure out which code is the actual culprit.
What could be helpful is to be able to profile the application once it freezes; I'm pretty sure the profiler will immediately show the actual bottleneck. I can successfully start the profiler (Performance tab) before the freeze happens, but once the application freezes, when I click on Stop button, the Loading profile window is stuck at zero percent (I waited for fifteen minutes just to be sure, it's still at zero), so I suppose that it's frozen as well.
Therefore my question is:
How do I find what causes the application to freeze when I'm unable to figure it out by simply debugging the application?
To answer my own question, the solution was to use a different browser. Surprisingly, Firefox let me profile the application during the freeze. The remaining part was easy, as I expected: by comparing the profiling results before the freeze with the ones after it, one could figure which code is executed repeatedly.
Thanks to Aleksey Solovey as well for his comment.

I'm making a codename one app with geofencing but it seems to stop calling back after it's gone into the background for a while

I'm working on an app using geo fences but I'm hitting some issues.
I've been testing on Android predominantly so far.
a) I set up the geo-fence and it triggers fine for enters and exit events.
However, after an extended period time (such as a few hours or overnight) the events stop until the app is opened again.
b) My other issue is the geo-fence exit seems to trigger even when I haven't moved at all, and definitely not outside of the radius (150 meters).
I've looked at https://www.codenameone.com/javadoc/com/codename1/location/Geofence.html, and my code is very similar to the example.
Are there any other build hints I need to make it more accurate and persist in the background?
Geofencing should only be added once, it's a very flaky API in the native OS especially when it comes to background behavior that breaks frequently with OS updates.
Use something like:
if(Preferences.get("AddedGeofence", false)) {
addGeofenceBinding();
Preferences.set("AddedGeofence", true);
}
And see if this works.

Why HTML/Web UI response slower than Native UI?

I can't understand, Why HTML/Web UI response slower than WinForms/WPF/Android View/Native UI?
The Native UI also have styles, elements nesting, events than the CSS, DOM, javascript events of the Web UI.
Event response time includes: focus changing, dropdown, scrolling, animation moving, animation resizing, etc.
The DOM tree insertion/replacing is also slow, inserting 10000 chars html will cost 100 ms in google chrome in android 4.0 while parsing its template only cost 20 ms(jQuery micro template).
I releazied maybe the biggest factor that slowdown event response is:
The UI locking between parallel javascript processes;
The rendering engine is too slow to process the new UI changing messages from javascript workers, especially when the browser rendering engine is busy with the last UI updating(because of the point 3);
The html layout method (for example: css cascading, inline flow layout, responsive layout etc) may slow down partial UI updating.
Parsing html/xml cost long time, a hint: Android view inflation relies heavily on pre-processing of XML files that is done at build time(http://developer.android.com/reference/android/view/LayoutInflater.html)
A subset of HTML and CSS standards maybe the future solution for webview app development:
http://www.silexlabs.org/haxe/cocktail/
http://www.terrainformatica.com/htmlayout/
http://www.nativecss.com/
http://www.pixate.com/
https://github.com/tombenner/nui
http://steelratstory.com/steelrat-products/wrathwebkit
http://trac.webkit.org/wiki/EFLWebKit
https://github.com/WebKitNix/webkitnix
http://qt-project.org/doc/qt-4.8/richtext-html-subset.html
http://sealedabstract.com/rants/why-mobile-web-apps-are-slow/
A pile of native UI markup languages: http://en.wikipedia.org/wiki/User_interface_markup_language
why there is not a simplified HTML standard and a simplified Webcore layout engine to replace these native UIML?
Maybe we could realize a subset html in kivy.org project.
PC, android browser = application thread + ui thread
iOS browser = application thread + ui data thread + ui hardware thread(CoreAnimation/OpenGL ES)
In ios browser, application thread could directly call ui hardware thread.
If Web UI is completely implemented by JavaScript on the client side, the difference from WinForms/Native UI will be trivial.
However, in most cases, the Web UI triggers some Web request to the Web server, then it has to go through the following steps to achieve the same effect as a WinForms/Native app:
Send a HTTP request (GET/POST/...) to the Web server
The Web server is an executable (in the format of an external app or a service) listening to one or multiple ports. When it receives the request, parses it, and finds the Web application.
Web server executes backend (server-side) logic within application.
Web application such as ASP.NET is pre-compiled. Time complexity of this step could be very close to a Windows app.
Web server renders the result into markup and sends it back to the client
Client (Browser) parses the result and updates the UI if necessary.
Controls/images/other resources in a Web page normally take a little longer to render within a browser than a Windows app renders its display.
Even the Web server is local, the cost generated the data parsing/formatting/transfer cannot be simply ignored.
On the other hand, an application with WinForms/Native UI typically maintains a message loop, which is active and hosted in machine code. A UI request normally just triggers a lookup in the message table and then execute the backend logic (Step 2 in the above)
When it returns result and updates UI, it can be simply binary data structure (doesn't need to be in markup), and doesn't reply another application(browser) to render to the screen.
Lastly, a WinForms/Native application normally has full control to maintain multiple threads to update UI gradually, while a Web application has no direct control over that type of server-side resources.
UPDATE:When we compare a Web application and a Windows/WPF (or native) application consuming a same Web service to partially update their UIs
The two UIs should respond and refresh with ignorable speed difference. The implementation difference between binary & scripting execution to respond and refresh UI is almost nothing.
Neither of the UIs needs to reconstruct the control tree and refresh entire appearance. Given same conditions, they could have same CPU priority, memory/virtual memory caching, and same/close number of kernel object & GDI handles at process/thread level.
In this case, as you described, there should be almost no visual difference.
UPDATE 2:
Actually event handling mechanisms in Web and Windows apps are similar. DOM has event bubbling. Similarly, MFC has command routing; Winforms has its event flow; WPF has event bubbling and tunnelling, and so on. The idea is a UI event might not strictly belong to one control and a control has some way to claim an event has been "handled". For standard controls, focus changing, text changing, dropdown, scrolling events should have similar client-side response time for both Web and Windows apps.
Performancewise, rendering is the biggest difference. Web apps have limited control of "device context" because a Web page is hosted by an external application - the Web browser. Windows applications can implement animation effects using GPU resources like WPF and speed up rendering by refreshing the "device context" partially. That's why HTML5 canvas makes Web developers excited while Windows game developers have been using OpenGL/DirectX for over 10 years.
UPDATE 3:
Each Web browser engine (http://en.wikipedia.org/wiki/Layout_engine) has its own implementation of rendering DOM, CSS; and implementation of (CSS) selectors. Moving and resizing elements within a Web page is changing DOM, CSS (tree) setup. The selector and rendering performance highly depends on the Web browser engine.
UI operations could make selectors go through unnecessary steps to update UI.
A Web page doesn't have control to inform the browser to do partial rendering.
which make fancy JavaScript controls (some jQuery UI, dojo, Ext JS) cannot be real-time fast, usually slower than Flash controls.
The time spent on the client is negligible compared to the time the data spends travelling over the network. The actual render time of a Windows form or a webpage in a browser is measured in (tens or maybe hundreds) of microseconds. Sending a request to a server and getting the result back is measured in milliseconds.
You can confirm this quite easily:
Create a simple Winforms application, time it.
Create a similar Web-based application. Run it on the webserver on your own PC, I.E. //localhost/myapp.asp and time it.
Run it on a remote webserver and time it.
You'll see that 1 is fastest followed closely by 2 (a little slower, interpreting the HTML, the CSS etc) and 3 is vastly slower because of the network time.
To answer your question, the difference due almost entirely to network delays, which are an order of magnitude greater than local processing time.
EDIT: It would be kind of the downvoters to add a comment explaining why.
3 big differences
WebUI apps are run within a browser, which then depends on how well the browser is optimized.
The browser also has its own javascript jvm. another process that has to run and interpret the code before it runs.
All of this is an extra layer that is on top of the native OS. If you were to bring up the activity monitor of you computer and bring up a web page in your browser, you will notice what a resource hog web browsers are.
Native UI elements have graphics acceleration support. depending on the os, native ui templates are compiled to a native format that does not have to be parsed for rendering.
One thing to keep in mind is that the browser itself is a native application, so anything built for the browser to run is inherently written with (at least) one additional layer of abstraction, versus something written directly for native execution.
It's also worth noting such dynamics as this:
300ms tap delay, gone away
http://updates.html5rocks.com/2013/12/300ms-tap-delay-gone-away
The initial impetus for this artificial delay was to support pinch-zooming vs other touch interactions -- that is, slower responsiveness in this case was a deliberate way to disambiguate different user actions.
Granted, while this is a rather specific use-case, the general concept does serve as an example of the different considerations for browser-based vs native implementations. That is, browser-based experiences include some of the usual framework cost of solving for a wide variety of interactions and content, whereas native experiences are naturally tailored more specifically to only listen for / respond to the desired interaction models.
Throughout the implementation, many tiny parts (such as this) are slimmer and more focused in a raw native version, which can contribute to the general effect of better responsiveness.
Only in substandard browsers (this includes all Android browsers, all Mac OS browsers, all Linux browsers, and worst of all every version of Google Chrome). These are badly written, unoptimised browsers with no concern for touchscreen latency, UI responsiveness and smooth scrolling. They lock up and stutter during any kind of CPU activity, disk or network I/O and user input.
Superior browsers such as Internet Explorer 11 or iOS Safari are sometimes even more responsive than unoptimised native apps.
Basically only Windows 8.1 and iOS have responsive browsers. All other browsers are inferior as far as UI responsiveness is concerned. The difference is really huge. IE11 and iOS Safari obliterate other browsers in UI latency and smoothness.

Why does SoundPlayer intermittently hang on playback?

I have a WPF application in which I'm using SoundPlayer to play several short sounds such as keyboard clicks. Sometimes, seemingly at random, the sounds will stop playing. When I navigate away from the page the sounds will then play all at once in one screeching playback.
My question is, are there any obvious reasons as to why this would happen?
I've tried several things but because I can't consistently reproduce the issue it's hard to find the cause. The sounds are used throughout the application, so I load them in app.xaml.cs into an application scoped static collection. I call SoundPlayer.Load() to ensure they're loaded into memory straight away.
Like I said, this never stops working completely. The play backs seem to pile up until navigating to another page where they all play at once.
One other thing that may have an impact is that I am displaying a webcam feed in the application. The webcam feed is loaded using the DirectShow.NET library. I'm not sure if loading graphs can have any adverse effect on the playback of sound.
I suppose the web cam is updating a UI element which will cause the UI thread to be pretty busy, in that case you probably do not want to use SoundPlayer.PlaySync() or SoundPlayer.Load which both block the current thread.
Instead try SoundPlayer.LoadAsync() and SoundPlayer.Play() which use a separate thread.

How to increase the performance of WPF Application

I have developed WPF Application. In that application iam loading 200mb photos to the listbox.After that Iam adding those images to canvas.While adding photos to canvas after sometime (i.e; after adding 10mb images)iam getting Some error like ----
*****The CLR has been unable to transition from COM context 0x10b46f0 to COM context 0x10b4860 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.*****
Is there any way to increase the performance of my application. I need a solution for this problem.
Any Suggestions for this.
Don't load all 200 mb of photos into the listbox all at once on your UI thread. Will the user be looking at 200 mb all at once? It'll take some work on your part, but you're going to need to do some delayed loading of the images from a background thread.
Take a look at this article (Advanced Techniques To Avoid And Detect Deadlocks In .NET Apps), it may help.
This looks like two questions, the first is that you are loading images in a background thread, but not doing it correctly; thus, the COM error. Double check that you are have a STAThread application and that the image loading thread is not interacting with the WPF dispatch thread incorrectly. Here's a discussion MTA vs. STA; however, WPF needs STA, and it's a loosing battle to fight it.
The second question seems to be how should one do this; that is, loading a bunch of images for display. I would look into using a lazy data binding of the ListView and let the virtualizing presenter that's built into is manage the loading/display of the images.
Here's some docs on using a view-model. The viewmodel could coordinate the image load and provide the ListView with a binding source that would automatically get the application working.
A simpler alternative might be to start up a background thread and load the images into an ObservableCollection<>, bind that to the ListView and let the framework deal with the display.
I second what Greg D said, loading 200mb of images sounds like a recipe for problems.

Resources