Best practice to handle thread of loading activity - java

I have an activity that displays a loading screen while a worker thread is loading my game. While loading the worker thread updates a textview on the activity to display its current status. When finished it will close the loading activity and start the actual game activity.
The worker thread is created in the onCreate() method and is given a newly created handler.
However what happens when the activity is destroyed and restarted e.g. by orientation change? IMHO the onCreate() methods would create a new worker thread while the first one is still loading, so now I got multiple worker threads doing the same.
What is the best way to prevent this and inform the worker thread about the new activity (so it can post its status updates).

Have you tied the DroidFu library? It has a class named BetterAsyncTask that seems to be targeted at getting rid of the problem you're talking about. You can find the library here ( https://github.com/kaeppler/droid-fu ) and an article about your problem and droidfu here ( http://brainflush.wordpress.com/2009/11/16/introducing-droid-fu-for-android-betteractivity-betterservice-and-betterasynctask/ - see the "That Dratted AsyncTask" section).

Related

Runnables and Activities

I have currently the following problem:
I got a server that provides and API via Google Protobuf. A Program (in this case an Android App) can request informations. I have an Activity in Android that will request Informations in the Background via a Runnable, which will then process the network request and dispatch to a function on the mainthread to update the UI with the new informations. Therefore I give the runnable a final interface with the function to dispatch which is implemented by the Activity. Now as the network stuff happens in the background and the UI should not block (e.g. with a Loading Spinner) I dont know what happens when the user switches to another Activity while the Runnable is still active. Will it still dispatch properly even if there is another Activity active? What is good design practice to solve this.
Of course I thought about adding a variable to the Runnable to mark it as dont dispatch, but there still could be race conditions (it gets dispatched while the user hits the back button, which would already have the dispatched function in the queue for the mainthread before marking the Runnable as aborted).
If you need any additional informations, please ask, I am happy to provide them.

Give background thread two handlers to talk to different activities?

I started Android a week ago and I have a design question.
I have two activities A and B. I'm currently on activity A. In activity A I start a thread that listens to network messages. On receiving start in the background thread over the network, I need to go into activity B.
Question: Can I simply call startActivity(B.class) from the background thread?
If not, I suppose I use a Handler to call startActivity(B.class) from activity A thread.
Question: Will my background thread still continue to execute once activity A, the one that created it is destroyed, provided I take care that there are no dead references?
Eventually I receive a stop message in the background thread, again, over the network. Now I need to go back to activity A (or some other activity).
Question: Should I replace the handler instance in the background thread class with a new handler instance created in Activity B? I reckon I'll have to pass the thread object to activity B when I start it. I'll presumably have to take care of the race condition when switching out the handler instances.
All of this seems... complicated. Is there a more elegant way to achieve this? Services? Loopers? All of this is new and the tools/design choices are a bit confusing.
If you are having multiple Activities then this isn't the ideal way of doing it.
Once Activity destroys your thread will have no more reference though it is running in the background. Use a singleton class to create the thread and register your respective handlers to that class, you will be able to communicate to the activities easily through these handlers.

how to modify a textview from diffent class in different thread - Android Studio

First of all, I'm not an expert, so I hope to explain in the right way and hopefully to get replies that are not too complex.
I have the main activity that run in a new thread. let's call it "thread-1", some operations (exchane data between server and client .
thread-1 remains alive forever.
The main activity after some time open a new activity, let's call it activity-2
activity-2 has a textView, let's call it textView-2.
After some time the running thread-1 invoking a static method, inside a Java class, that has to modify in real time textView.
How can I do that?
Thank you very much in advance.
Fausto
You cannot (and shouldn't) do what you describe. The first Activity is no longer in a running state once the second Activity is started. Their lifecycle callbacks are called on the same thread: the main thread of your Activity. Your first Activity should have no direct ties like this to your second Activity. If you do need a secondary background thread, you must start it manually or use something else like AsyncTask or even RxJava's observers. But, you cannot directly change the state of View objects while on other threads, they can only be altered when running in the context of your main thread.
at the end of the story, I solved in this way:
Activity-2 launch a listener thread (by a while cycle)
Thread-1 of activity-1, when it wants to change a TextView of activity-2 , sends a message to the listener (modifying the value of a static var of the listener)
the listener receive the message and send it to Activity-2 (by an Handle), then finally it changes the TextView
I inserted a control that exit from the while cycle when not needed anymore
I hope can helps someone else...

Android Intent open new activities but did not close the old one

I searched through most answers here and all suggest we add a flag to the intent to kill old activities. The problem is my activity only receive intents from other app and has no control over it.
More specifically, my activity receive an intent to load a picture, then it uses Asynctask to load and do some complicated background processing of that picture, say, may be 2 minutes.
If the user at this moment back out (assuming that only onStop is called, not yet onDestroy) and share another picture to the app , this will start a new activity, and the previous activity cannot be accessed, but its Asynctask hold up the thread so that my new activity just freeze without starting its own Asynctask.
(I later tried the parallel thread executor, but this doesn't stop the old thread from running, thus consuming computational resources).
Any idea what I should do?
(I don't want to stop the task in onStop as this is to easy to be called. But I do want to stop the task if new picture is shared, since it is no longer needed.)
(The Asynctask will spit out a huge array of self-defined Objects declared in the main activity, and thus the activity gets immediate updates of the result from the background process, and the UI updates immediately after onPostExecute is called.)
EDIT:
It seems that your problem is that you're trying to do all this image processing work in asynctasks launched by your activity. Have you considered changing your app architecture to rely all this background processing to a service?
You can use the activity to show some UI information while you process the image in your service, or if you don't need this UI just simply communicate with the service (through broadcast, for example) to provide it the image and let the service show some information of the process through notifications.
If you don't want to keep your activity alive when you exit it you can use
android:noHistory="true" in your activity declaration at the manifest
More info here
This is the workaround, and seems it is working very well for the moment:
After getting a sharedpreference prefs, do this in onCreate:
prefs.edit().putBoolean("ForceClose", true).commit();
In the onPreExecute() of the AsyncTask, put:
prefs.edit().putBoolean("ForceClose", false).commit();
In the doInBackground() of the AsyncTask, constantly check for
if (prefs.getBoolean("ForceClose", false))
cancel(true);
and call finish() in onCancelled() to finish off the activity.

Threads interrupted when new activity is started. Android

I have a slightly strange thing happening in my code atm, which I don't understand... I would much appreciate any input anyone may have.
So here's the issue:
In my main Activity I fire a Service, using an Intent, when a button is pressed on screen. The Service instantiates 22 Runnable objects each of which read data constantly from 22 separate flat files. The data is fed into a matrix of objects (64 x 64). In my main Activity I have another button which starts a new Activity to visualises the data in the matrix. So when I press it it accesses the data stored in the objects at the same time as the 22 threads are feeding data into them. It is my understanding this kind of operation is the main reason to use threads! However, when I start the new activity it seams to interrupt and/or kill the threads as they no longer print their Log.d messages to logcat...
Is it a case that I need to bind my Activity to my Service to access data that it is processing or are the thread independent of the Service as my common sense would tell me??!
Thanks in advance for any advice!

Categories

Resources