Sluggish unresponsive touches on Android - android

I am porting my game, from iOS to Android. Mostly, it's working just fine. I'm mostly using C/C++ code, with the NDK / JNI, and a little Java to manage the app life-cycle and send touches and accelerometer info to my game.
As far as I can tell, there are 2 threads, the main UI thread, and a thread created by GLSurfaceView to handle display and flipping OpenGL back-buffers etc.
So, all is working well, apart from the touches. They feel sluggish and unresponsive, compared to other apps I have tried on my devices. After doing some research, I believe the issue may relate to how I am using threads. Specifically, I think, it could be related to not sleeping the display thread after it does it's work, and so, it's holding things up on the main UI thread. Does that sound plausible?
I tried computing how many ms I need the GLSurfaceView display thread to sleep, and then sleep(), and it improves the touches, but the animation is no longer a constant 60FPS on my devices. My suspicion is that I am computing the number of ms to sleep for the previous frame, and using that number to sleep for the current frame.
Or, it could be something altogether different? I don't know. I'm still very new to Android...
Hope someone can shed some light on the matter, or point me in the right direction.
Thanks,

You don't have to sleep the GL thread. In fact, I'd say sleeping the GL thread would make it even more sluggish since it's the thing rendering the images on the screen.
Sluggish UI is caused primarily by the main UI thread being held up. If you're doing a lot of processing on the main thread (accelerometer data for example), the main thread will have to do the work first and THEN handle your user input. This can give the "feeling" of sluggishness. All touch events and non-opengl drawing events must happen in the UI thread. Anything else can occur in a background thread which wouldn't block the UI thread for an extended period of time.
Aside from that, the other possibility is you're simply overloading the processor. Your GL thread might be taking a long time to draw. It's probably receiving and handling touch events and accelerometer data. However, if the render takes a really long time, then you'd be seeing out-dated data. Thus, it again feels "sluggish". You mentioned that it's not a constant 60 FPS so this is a very real possibility. You may have optimize your drawing code so the render is faster.

Related

Why can't UI thread and Render thread run at the same time?

I am a mediocore android developer for years. I like android but there's a big problem; frame drops. Even the most powerful ones can stutter so frequently while IOS devices can run at constant 60fps. I just can't understand why. I want to know it. So first thing i did was watching an I/O presentation about performance. And i didn't really understand one thing. Why can't ui and render thread run at the same time ? Yeah i know the basics like render thread can't know what to render while ui thread is doing it's thing but why can't render thread render the frame before? You can see the video here:
https://youtu.be/9HtTL_RO2wI?t=491
And here's a diagram what am i asking for:
You get the idea. I don't know about low level things about android, can anyone explain this like i'm five.
Your process' main thread is responsible for the rendering of the frames that will be presented to the user, so you should keep the code running there as fast and light as possible. If you have to do some heavy processing or access any IO (network, sdcard, etc) that may impact on the fluidity of the application since the thread may be waiting for a response.
As a good practice you should start that IO access/heavy processing on another thread to run in background and let the system decide the priority to run it, if necessary is recommended to present some feedback to the user like a ProgressBar or something to indicate that something is being processed.
Also, the Render Thread need to know what to render before it does it, so the UI Thread have to process which information the app would like to present to the user.
As #JonGoodwin points out, they both run in parallel, but usually in two cores of the same processor, as nowadays phones have at least two cores. Both threads are run in CPU, where RenderThread sends rendering commands to the GPU. Notice that this is true since API 21 (RenderThread is what enables things like ripple effect).
The problem, though, is what #LucianoFerruzzi points out: usually poor code that does too many things in the UI thread (RenderThread is not accessible, at least not with standard mechanisms).
Also, see the following episode of Android Developers Backstage: Episode 74: Graphics

Android App high cpu usage and battery drain

I've been working on an android game for awhile now. I have the basic game implemented so now I'm going back and trying to optimize. It seems like the battery drain and CPU usage are too high for what I'm doing. I really only have my main thread and then all the drawing and updating is done on a separate thread.
Below is the code for the actual game thread that does updating and all the drawing. All of the actual code has been removed, what's left is what I've been experimenting with to figure out the abnormal CPU usage/battery drain.
So basically if I start the below thread with only an infinite while loop the app uses about 315mAh or about 9% of my phones battery in 30 minutes of use. If I start the thread with no code inside the run method so that it expires after one run through it uses roughly 70mAh or 2% of the phone battery in the same amount of time. The CPU usage also jumps from 2%-3% without the thread running to about 14%-15% when the thread running and just running the infinite loop.
To summarize it seems like running the thread with only an infinite while loop, that does nothing, increases the battery usage by 7% over 30 minutes. I don't see how this is possible and think I must be missing something. I'll keep working to figure this out but there's no more code to take out. If anyone has any suggestions or can provide some insight as to why this is happening I'd greatly appreciate it. Thanks in advance.
class InnerThread extends Thread
{
public InnerThread()
{
super();
}
public void run()
{
while(true){}
}
}
Loops with no delay or pacing are notorious for hogging CPU and battery. Think carefully about whether you really need to be processing continuously, or if once per frame, once per arbitrary time interval, or once each time some external event occurs would be sufficient. Try adding a small arbitrary delay in the loop, and you'll probably see an immediate improvement.
Many games use a main game loop. That's a searchable term. Basically, an endless loop performs some computations, draws a frame, then usually sleeps for some time. (See SystemClock.sleep() vs. Thread.sleep().) Your main loop could pass a frame number and timestamp to the rest of your code. You might compute the positions of moving objects every frame, but you could do more complex things like update the AI of your enemies only at certain intervals of time or frames. If you use a game engine like Unity, the main loop is still there, but you don't write it yourself. You just write the code that it calls every frame.
while(true) is a classical endless loop and probably not required in Java.
it does not even matter on which thread it runs, it's most likely draining the juice.
see Are "while(true)" loops so bad?
I went through and edited my code. Utilizing thread.sleep to limit the overall drawing and updating code to 60 frames per second. Also I made use of the Object.wait() and Object.notify() methods to reduce the unnecessary processing of the thread. I've seen huge improvements, thanks for the help, I really appreciate it. My problem was most definitely that I was wasting battery and CPU power processing nothing.

Worker Threads On Single Core Device

I have reposted my question from Android Enthusiasts here, as this is more of a programming question, and it was recommended.
Anyway. Here it is:
I am making an app, that changes the build.prop of key values for a ROM. However, Android often gives me an ANR warning, as I am doing all the work on the UI thread. On the Android documentation, it tells me that I should use worker threads, and not do any work in the UI thread. But, I am building this system app to go with a ROM for a single core device.
Why would I want to use worker threads, as isn't this less efficient? As, Android has to halt the UI thread, load the worker thread, and when the UI is used again, halt the worker thread and load the UI thread again. Isn't this less efficient?
So, Should I use worker threads (Which slows the UI thread down anyway) or just do all of my work on the UI thread *Even if the application UI is really slow)?
If your users were robots, your logic would make perfect sense. No context switching equals (very slightly) less overall computation time. You could benchmark it and see how much exactly.
However, in the present (and near future) your users will most likely be humans and with that you need to start thinking of psychology: A moving progress bar or responsiveness in general will give your users the impression that the the task is actually taking a shorter time than without any sort of feedback. The subjective speed is much higher with feedback.
There exist numerous papers on the subject of subjective speed, the first one I could find on the web has a nice comparison of progress bars in a video (basically, some bars seem to go faster than others, thus reducing the subjective overall wait time).
Use worker threads.
As you've said, doing everything on the UI thread locks your UI until the operation is completed. This means you can't update progress, can't handle input events (such as the user pressing a cancel button), etc.
Your concern about the speed of context switching is misplaced - this happens all the time anyway, as core system processes and other apps run in the background. Some quick Googling shows that context switching a thread within the same process is typically faster than a process-level context switch anyway. There is slightly more overhead introduced by creating the threads and then the subsequent context switches, but it's likely to be minute - especially if you only have the 1 thread doing the work. For the reasons I've listed above alone (UI updates and the ability to accept user input), take the few-millisecond overall performance hit.

Android Render and Physics on separate threads?

I recently had problem getting my physics to stop racing ahead of my rendering (they were on the same thread), After a few months, I resolved the problem in about 20 minutes by creating a new thread and putting by physics into that.
I find that having them completely separate from each other gives me far greater control and now my sprites are moving consistently across all screens at all frame rates.
My question is, is it 'better' to put logic and rendering in the same thread or separate threads? The latter seems better to me but does it cause any problems? (does if affect battery life for example?)
Thank you
Yeah it is definitely better to use multiple threads, especially if the calculation is non-trivial, in which case you could experience the dreaded "Activity Not Responding" dialog.
Something that I would definitely look into would be AsyncTasks http://developer.android.com/reference/android/os/AsyncTask.html . Essentially, you would perform all of your physics calculation in the doInBackground method(which is running in a background thread) and then periodically call publishProgress from within that(which will execute the 'onProgressUpdate' callback where you will do all of your rendering on the UI thread).
Actually using different threads for performing logic and rendering UI is really and always appreciated.and it correct also.
But to handle/manage the multiple thread is the harder responsibility for a programmer.
And as the threads also increase the battery consumption, so we should always use thread very carefully.
So the final outcome is use threads but carefully. because thread are useful is used optimally but dangerous is not used carefully.
You said...
"I'm using surfaceView which as I understand it, uses a separate thread for rendering (separate from the UI thread) - so I have 3 threads"
It sounds like you're assuming that by extending SurfaceView, you're automatically provided with another underlying thread for the Surface which is separate from the UI thread. I believe that this is NOT the case.
From the Android developer reference for SurfaceView: "One of the purposes of this class is to provide a surface in which a secondary thread can render into the screen."
The key word being can. You still have to spawn the separate thread yourself, the SurfaceView just makes it easier to draw to a canvas in a separate thread.
If you take LunarLander as an example, it has just two threads: the UI thread, and a manually-spawned 'LunarThread' in which the physics are updated and the canvas (via SurfaceHolder.lockCanvas()) is drawn to, as fast as possible, independent of the UI thread.

Android: OpenGL rendering pauses when heavy background task running

I am rendering objects via OpenGL, and got a nice smooth framerate of 60fps in most situations.
UNTIL I do something heavy in a background thread, like fetching stuff from a REST API, processing it, and adding objects to the graph (low-priority stuff, I care more about UI fluidity). The renderer will then pause for a very long period, up to 1 second (ca. as long as the background thread runs), and then resume as if nothing had happened. I noticed this because an animation is started at the same time, and it gets stuck for this period. The background thread is set to minimum priority, and garbage collection does take up to 100-200ms, but not the whole second. When I set a debug point anywhere in the background task, rendering continues just fine, without any delays.
Is it possible that my heavy background thread starves the OpenGL thread? If so, what can I do?
Of course! A GPU needs to be fed data, and that's done by the CPU. So, if something in the system bottlenecks, like I/O or CPU processing, then the GPU can't get fed. For example, animation is traditionally done on the CPU. This is why you get a lot of games on the PC getting higher frame rates with the same graphic chips but with different CPUs.
I also agree that profiling is a very good idea. If you can, I would suggest profiling to make sure it's actually the REST call, or if the REST call is one of many things
One thing I noticed about REST processing, and this happened to me. Since REST sometimes processes a lot of strings, and if you don't use StringBuilder, you can end up firing off a lot of garbage collection. However, it doesn't sound like you are getting this.

Categories

Resources