writing a small android game for a university assignment and just wanted to check what I'm doing is correct.
I'm creating a Mastermind type game and am unsure how to handle basic game operations such as checking if a guess is correct.
Am I correct in thinking that the best way to handle these operations is to create inner classes that extend Async to avoid UI lockup?
If not could anyone suggest any other ways?
Cheers!
After many weeks of developing my application, AsyncTask is what I used instead of standard threads. AyncTasks are less likely to get killed, they create a worker thread and handlers by themselves so you can update GUI through it more easily than standard threads. But remember that only one instance of AsyncTask can work at a time.
I don't think you need AsyncTask for this game at all. AsyncTask is a process for which you do not know how long it will take and you don't want to block your UI thread, like downloading something from Internet.
Your game can be completly events driven. Whenever the user makes a move you call your methods.
If you want to have animations while the user thinks then SurfaceView can do the job.
Related
AFAIK, android uses Single thread architecture, where all UI components event are dispatched,i.e. main thread or UI thread.
But why we cannot perform UI operations on separate thread other than main thread?
The main problem is related to the context. In a background thread you could update some UI stuff which is not in the current context. This is one of the reason.
UPDATE:
From the Android developer guide:
Additionally, the Andoid UI toolkit is not thread-safe. So, you must
not manipulate your UI from a worker thread—you must do all
manipulation to your user interface from the UI thread. Thus, there
are simply two rules to Android's single thread model:
Do not block the UI thread
Do not access the Android UI toolkit from outside the UI thread
You can read more on thread safety from [1] [2] and you can read even [3] with a small exmaple and explenation!
Hope that now it is more clear sorry for the short and quick answer before :)
Well, first of all I need to state that this is a design level problem that has been discussed by many generations of programmers :)
Now technical details:
A GUI framework is a very complex thing. A GUI framework needs to display (draw) certain views (or windows) and route external (mostly user) inputs to the view that the input is targeted to. Now, to manage the screen with views with proper event dispatch to each view, all views shall be part of a graph and the simplest form of such a graph is a tree. So, you essentially have a tree of views to manage - where information should be fed to a root view from where your whole event routing takes place to child views.
Naturally, one dedicated thread to do manage this view hierarchy and event routing by monitoring a message queue to which all these drawing and input events are posted - by itself or any other threads - is a neat and simple solution. Any other solution that involves more than a thread will make the already complex view management and event routing code prone to dead/live locks.
Along with these technical details, you need to keep it in mind that you are trying to do business with a framework which is going to be used by other people who usually don't have faintest idea about the inner details of your architecture. Introduce threading support in such a framework is an open invitation for synchronization bugs (read: deadlocks, grumpy end users who are programmers AND ultimately bad business).
Android (and 99% other GUI toolkits) adopts this method. Simply because it makes things simpler and less error prone to have one main thread to deal with all error prone processing. All other threads are free to request it to do things by posting messages to the main thread's message queue. It is a balance between complexity and stability.
The only drawback of this approach is smooth updates of views - if you have many views to update simultaneously, OR your view hierarchy itself is really nested and complex. This drawback of this single threaded architecture manifest itself in pretty obvious forms in Android like:
Animating multiple views simultaneously is never smooth - unlike iOS where they have taken the pains to move certain parts of this operation to more than one threads of execution.
Android documentation need to remind the programmer all the time not to do lengthy operations in main thread AND to avoid deeply nested view hierarchies.
I'm developing an app in which I pretend to invoke a REST service for typical CRUD operations. Since I want to separate the requests processing from the UI thread, I'm planning to use an AsyncTask to do the separate work. However, my question here is: how should I desing my AsyncTask(s) model? Should I use one AsyncTask for all CRUD operations (is this even feasible?), or use i.e. 4 AsyncTasks (create, delete, update, retrieve)?
Thanks in advance
I would go with a ContentProvider instead of using AsyncTask.
According to this thread:
https://groups.google.com/forum/?fromgroups#!topic/android-developers/8M0RTFfO7-M%5B1-25%5D
on Android 4 AsyncTasks will be sequential.
So, for that reason alone your solution may be less than optimal.
But, ContentProvider just makes more sense for what you are trying to do, as what happens behind the CRUD calls the user doesn't care. You may want to run this on a separate thread though, as being on the UI thread for too long is bad.
It is really up to you, and perhaps, the REST service which you are consuming.
Some things to consider:
Is the service general enough that it would be easy to do everything in a with a single AsyncTask?
Will your code be easier to read and understand if you do things with a single AsyncTask? I would tend to think that it would be easier to read if you did one AsyncTask for each operation. (ie, CreateTask, UpdateTask...)
Will I get the reusability that I am after with my choice (whatever it is)?
Personally, I would create 4 distinct AsyncTask's, and any reusable code I might put in a base class, but again, it is really up to you for what is going to work best for you.
Personally, I use the Loader framework, available with the compatibility library. I have a subclass of AsyncTaskLoader for each of the CRUD operations, and it works really well!
I guess if you prefer to avoid having lots of classes you could use the same task (i.e. the create and update could technically fit in the same task) - when you subclass your AsyncTaskLoader create a setParameters(...) method which you can call when you create the loader in onCreateLoader().
It might help to read the above after you've reviewed the Loader documentation.
I'am developing an application which is totally based on fetching data from web services.
In one activity I have to call almost 5 6 different web services which displays different information. This application is target v 2.3 to 4.x, as there are no network communication allowed on main ui thread so I am making 5 6 AsyncTask classes, because its post execute helps me a lot in displaying.
Now I am confused is this approach right or wrong, making 5 6 AsyncTask classes(can't reduce the number of web services or call in one AsyncTask because I have to check data again and again). Is this a good approach or should I change my pattern, and then switch to what approach.
Using this approach my application is working very nice and smooth on all devices.
I think that's a good pattern. It fits nicely into Object-Oriented design and each one performs it's own task.
If your web calls are all directly after each other, you could combine them into one huge AsyncTask if you really want to. That would definitely reduce the nice encapsulation you have now and would make it a lot harder for someone to maintain and debug down the line.
It sounds like what you have is good already, and if it's working well, why fix what's not broken.
I would assume that each ASyncTask class is an API request to the webservice, if so it is the right way of doing it. Any network operation should be done outside the UI thread.
There is also a better way of using ThreadPools to limit the number of Server requests you want to keep active at a time.
I'm trying to develop a game. It's a simple whack-a-mole type of game where something pops-up the screen and you click on it to kill it. I was thinking of giving the "moles" their own thread so that they can do their own animation, event handling, etc. in their own lifecycle until eventually killing themselves.
Will this kind of "each object has its own thread" implementation be good for an Android game?
Definitely not. Do not give each mole its own thread. This would be too much use of threads while it is needless to say that in this type of game you do not need such a number of threads. Just keep everything in the main thread and use some listeners to kill moles. (=make invisible)
Yes, it is a performance issue and a matter of developer's decision. Why should you create a thread for each mole? This is the right question because doing so is a far more unrealistic decision. Will each mole access a database? communicate with a server? I don't think so.
Anyway, since it is a mole on the screen, you will only need one instance of it that you can render/move it around/disable/etc in the main thread.
This could work, if there aren't a ton of objects, and a ton of activity for each object.
I would suggest thread pooling. Pull out inactive objects out of threads and put in active threads.
Stay single threaded until you actual need to change - especially for a simple game, you won't have the kinds of performance problems that need threading.
At any rate the general approach is not to thread out individual entities, but entire steps of algorithms performed across 100s or 1000s, or even entire systems (e.g. audio, physics etc.) - and perhaps the most extreme but common case is to split your rendering submission into its own thread for all rendering, with animation, physics, gameplay logic etc on another thread, in exchange for single frame latency on everything.
Not to mention that the overhead of having very many threads often becomes limiting - if you have 2 or 3 moles it might be fine, but if you have many more you will quickly reach the point of diminishing returns - not to mention the difficulties inherent in keeping many threads in sync and avoiding deadlocks, race conditions etc.
I've found a sample to download a large data file at the following link,
http://code.google.com/p/apps-for-android/source/browse/#svn/trunk/Samples/Downloader
It seems to be pretty nice (I haven't yet tested it). But I also have read some posts at the stackoverflow to do the same thing by using the AsyncTask class, not using the Thread class as the above sample.
What I want to know is, which should I use to achieve downloading a file? And if AsyncTask is better, would you point me to a sample code?
Disclaimer: i am not Android developer, answer comes from general experience.
Thread class is most suitable for long-running activities, not for asynchronous tasks. Except if you manage pool of workers, but still lifetime of thread is same or nearly same as application. Consider that creation of thread is expensive operation.
AsyncTasks and other helpers are usually for some single activities that you want to do in background so not to block the app. They are usually well managed by the platform and are cheap.
My opinion: use AsyncTask if you want to load pages occasionally. If your app will load pages all the time in the background consider thread.
For understanding what has to be used one must understand the nature of the task we are about to perform.
Suppose we are going to download large file.... would you being a user want to see it or rather let it run in the background?? i guess i dont mind running that task in the background(unless it is game and some graphics are being downloaded).
Taking this thought in mind, if we use the Asyntask, the user must have to keep the App open until the download operation has been completed; as three out of four methods of AsyncTask runs on the UI thread. (check out the link : https://developer.android.com/reference/android/os/AsyncTask)
In the other case where we are using the AsyncTask to download graphics file for a game, it would be completely fine to go for it.
So I believe it is better to go for Thread or even better to go for Service to download the content so that one may continue to work further on the app/ close the app or even run some other app.
These two options have an equal probability of being killed while download is in progress (when user switches to another app). Still, AsyncTask is less mess. For downloading large files, consider using a Service.
AsyncTasks in Android versions prior to 3.0 uses a pool of threads in background to execute the tasks, but in versions after 3.0, a single thread is used to execute the AsyncTasks.
If you need to make a lot of requests at the same time and your Android version is higher than 3.0, use a pool of threads, but if you only have to make a single download (not mind the Android version), use AsyncTask, it will be executed at a single background thread without problems, easier than manage a Thread by your own.