Pausing/Resuming A Game Thread Using wait() and notify() - Android - android

I have a main game thread but when the target score is achieved I have an activity that is launched called StageCleared which basically displays the stats to the user of their performance and then they can press a continue button to carry on with the game. This should switch focus back to the running thread that should continue execution, and thus display the game activity (with parameters i update after StageCleared has exectued).
It was suggested I use a package visible object that calls wait() on itself in the main game thread, and then notify() on itself from StageCleared in order to continue execution. My first problem is I can't seem to declare a package visible object that can be seen by all the classes in my package? Secondly, is this the best way to achieve what I'm intending to do or is there a better way?
Many thanks

To enable package visibile, leave the modifier blank:
static boolean mVarname = true;
mVarname is visible inside the package.
I work with a run flag to enable if the loop should do something or just "idle". I, too, dont know if this is a good way to do it :)

Use FutureTask and Executor, check it out in Java API.
It's like, you define the operation and FutureTask, and it'll wait until the task is completed.
Easier than wait()

Related

difference between onTouch and onClick listener and use of multithreading

I am trying to make some application in android (some kind of calculator app). In the app, on pressing the buttons a lot of conditions get checked using if-else. I am using onClickListener with the buttons, and so they are taking a slightly longer time to respond. So should I use multithreading to separate the logic from the main thread or rather use an onTouchListener with the buttons?
For the click event, keep using onClick, onTouch is used for tracking gestures.
It's not a good practice to do any logic operation inside the Main Thread. Leave it just for user interaction. You should consider use threading to avoid ANR (Application not responding). A good start is AsyncTask, that has it own method to do logic in a separete thread and update the UI on the Main Thread.
Please follow this link to get help with AsyncTask: https://stackoverflow.com/a/18827536/4973904
Hope that this could help you!
you should not do too much work on Main thread.The problem is not if else statements because conditional statements execute very fast but the logic you have written inside the if else blocks .may be your logic taking to much time to execute.
Solution:
if you want to perform extensive task , you should use some background thread or an alternative of this like Async task or Loaders.

Is using runOnUiThread inside AsyncTask inefficient and bad?

I know it sounds crazy that someone is using runOnUiThread inside AsyncTask. Somehow, it is working for me but I wanna know if it is an acceptable and robust approach or not. Here is the scenario:
I have an app in which after successful login, user is rendered to next screen. In this new screen, 3 different methods are loading different types of data from a web server. These methods are:
getMembersForList() : It loads the list of community members and shows it in a listview.
getProfileData() : It loads the profile of logged in user and shows his name , image etc on the screen.
getNotificationCounts : It loads the count of new notifications for the user.
I applied 3 different approaches for it :
(1) Calling all 3 methods simply in onCreate i.e. no exclusive thread is being used for any of the methods . In this case , the transition from login screen to this screen becomes very slow and black screen shows up for some time before this activity shows up.
(2) Calling getMembersForList() on UI thread and the other 2 methods on exclusive threads. In this case transition becomes fast and list shows up quickly but Notification counts and username etc. don't show up because WrongThreadException occurs saying that this thread can't touch other thread's views (TextViews for username, notification count etc. which are declared globally) . The same thing happens when I start these threads from an AsyncTask as well.
(3) Calling getMembersForList() on UI thread and then starting an AsyncTask in which the other 2 methods are being called in "runOnUiThread" inside doInBackground() method. This solves both the above issues. Now the screen transition is faster and the WrongThread exception is also not occuring.
So far the approach-(3) is working good for me but I am not sure if this is the right way to do it because runOnUiThread and AsyncTask are 2 completely opposite things. Can anyone please clear my doubts about this scenario. Thanx in advance.
Yes, use-cases like this are a big reason why the runOnUiThread() method exists in the first place. The idea is you allow your background thread(s)/AsyncTask instance(s) to run your lengthy operations in the background, and then provide a simple hook that they can use to update the interface when they have the result (or at arbitrary intervals, as different pieces of the result become available).
As long as that's what you're doing, then your usage is fine. What you want to avoid doing is performing a lengthy operation on the main thread, either directly or indirectly by passing in some lengthy operation from a background thread.
Of course you don't have to do it that way if you don't want to. You could use postExecute() instead. Or you could store the result somewhere and then use any sort of message-passing API to notify the main thread that the result is ready, and so on.
I would advice to run all the 3 calls in the asyncTask, and update the UI in the postExecute() of the AsyncTask after the background taks is complete, postExecute runs on UIthread so you need not call anything explicit to run them on UIthread.

Activity's background thread & configuration change

I have seen some discussion here on Stack Overflow related to using Activity.onRetainNonConfigurationInstance() to maintain a background thread started by one instance of an Activity and pass it to the next instance of the Activity which results, for example, when the phone's orientation changes from portrait to landscape.
The discussions do not specify exactly what can be done with the thread wrapped in the Object returned from onRetainNonConfigurationInstance().
For example:
1. Is there a way to actually keep the background thread running using this technique?
2. Do you need to somehow pause the thread when the previous instance of Activity is going away and then restart it again in the new instance?
Can anyone provide a short example?
Any details would be appreciated.
You can return anything you want to onRetainNonConfigurationInstance(). If you have a Thread that you want passed from one instance of the Activity to another, you can either return it directly, or put it inside another object that you return from onRetainNonConfigurationInstance(). You don't need to pause the thread or interact with it in any way. It just keeps running as if nothing happened.
The only thing you need to be concerned about is how the Thread interacts with the Activity (if at all). If the thread will call the Activity back (to indicate progress or something like that) then you somehow need to give the thread a reference to the new Activity, as the old Activity will be dead.
What do you want to do in your background thread?
EDIT (add more details about threads/activities):
Threads have their own lifetimes which are completely disconnected from Activities. If you create a Thread in an Activity and start it, it will run to completion no matter what your Activity does. The only thing that will stop the thread explicitly is if Android decides to kill your process (which it may do if your process contains no active activities).
The thread will continue to run. For an example of what you can do with this, you can check out the android Ignition project and its IgnitedAsyncTask (and related examples).
The idea is that you will maintain a reference to your thread (usually an AsyncTask) somewhere in your Activity, and occasionally your thread (again, especially if it's an AsyncTask) will require a reference to a Context in order to perform some kind of UI update upon the conclusion of its background task. You will need to make sure that the Context (and anything derived from it--like a TextView or the like) to which your thread has a reference is non-null, or else it will crash.
You might use getLastNonConfigurationInstance() to set your Activity's reference to the thread, and then call a setter on the thread to set its Context reference (to avoid any related null pointer crash).

Thread UI sleep withtout freezing scrollview

I'm trying to implements a game AI, and I got the following problem :
I'm calling a method from another class my UI Activity class, this method call itself some methods of the UI Activity class (to simulate click on screen among other things), and the things is, at the end of this method, I need to "pause" the game a few seconds to let the user see what did the AI.
So I tried running the method in another thread, but I got the error message providing from editing a widget from another thread. I tried to sleep the UI thread, but by doing that, the user can't use the scrollview anymore, and the changes aren't display before the sleep but after.
So I'd like to know how can I do this ?
(I've read some topics about AsyncTask, Handler, but can't make it work the way I need)
Thank's
You need runOnUiThread.
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
http://steve.odyfamily.com/?p=12

Structure App using Methods/threads

I know this is a fundamental java question, but i am relatively new to java.
How do i structure the code attached (monitoring) within a UI.
What the code does is just log values, and if certain conditions are activated, it does stuff. The loop () method does pretty much everything, but there are a few small things done by the preceding methods.
Let's say in the UI, I have a 'calibrate' button, which if pressed, runs a calibrate method/thread, and a 'monitoring' button which runs a different 'monitoring' method/thread. The problem is, these methods/threads are at the moment defined in their own project as classes. My ideas are along the lines that i need to construct these 2 classes and then call the methods i want from them in response to UI interaction. However, if i call just the method, for example:
if (monitoring button) {
monitoring.method1;
}
this means that i can't do anything in parallel to that, so I need to make what happens in those classes into thread somehow.
Cheers,
Rokky
Take a look at AsyncTask, this will allow you to run logic in a background thread, leaving your activity free to respond to the user.

Categories

Resources