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!
Related
I am learning Android app development from Udacity.com by Google engineers and they said,
"It is not a good idea to use 'AsyncTask' as it is not attached to an activity life cycle. The virtual machine will hold on to the activity object as long as the Asynctask is running, even after Android has called onDestroy( ) method for the activity and expect it to be discarded.
If you rotate your phone, the behavior is to destroy the current activity and instantiate a new one. The naive AsyncTask implementation now has two threads trying to do the same update. So it is not the best pattern for a potentially very long running background operation , such as fetching from web services. If you leave the app, the asyncTask will run as long as as the process is kept alive , but will run at a lower priority, and your process will be the first thing to be killed if the device needs more resources. "
1) If using AsyncTask is disadvantageous why was it created? What would have been the design philosophy or the cause to create it in spite of having services(or something similar to achieve same kind of functionality)?
2) What are the situations where Asynctask should be used for betterment compared to Services/similar options available in Android?
3) What are the situations/places Asynctask should never be used?
Please do not downvote this question. I searched Stackoverflow and I couldn't find a similar question.
Advantages of AsyncTask
Provides generic solution for all network calls
Publish progress to UI while executing.
Run Asynchronously
Easy to maintain and read.
Problems in AysncTask
When you rotate your screen, Activity gets destroyed, so AsyncTask will not have a valid reference to publish data from onPostExecute(). In order to retain it, you need to usesetRetainState(true) if calling from fragment or onConfigChanges() if calling from activity method of an activity.
If activity gets finished, AsyncTask execution will not cancelled automatically, you need to cancel them else they will keep on running in the background.
If any exception occurs while performing network task, you need to handle them manually.
Whereas AsycTask, Services, IntentService, Threads all run on different threads and all serve different purpose.
please read more detail here.
So you need to decide when to use which component while performing non UI operations.
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.
I'm trying to design an application that does two different tasks in parallel
each task start executing when the user presses a button in the activity "so I have three Activities two of them should do some tasks and the third one should collect the result".
When the user presses the button on the activity it will invoke a thread and then will Load the next Activity
In the third activity I have a button "I called it Send Button " that should stay inactive or disabled until all threads finish their work so at that moment it will be enabled and this activity contains plain text to show the result from these two threads and when the user presses this button it will send the information in the plain text to a web site.
My questions are : how can I run Threads in a different activity and send their result to another one? and how can I make that "Send Button" disabled until all threads finish their work.
I tried to make a while loop using a global variable in the onCreate method in the Third activity but it crashes the application and the activity didn't start up
You have two options to do a long running background task:
Using a thread which does your background work, with an singelton to access the results
Using a services which does the calculations
Depending on your actual use case the service is the first choice.
Use an Activity only when you need user interaction to your application. Else you can invoke both the threads using AsyncTask for your jobs(If you want the system to handle the worker threads for you. And unless you do not do any config changes on the fly -> performance hit).
Please keep in mind that, you should use AsyncTask only when the background jobs run for dew seconds. If you have a long running job, then use a service with a custom thread.
Hope this helped.
You can use AsyncTask. AsyncTask is one Class which is used to perform background processes without having threads. You can easily check the process is completed or not. Check this Tutorial. This can help you to understand how to run background process using an AsyncTask.
I have a small Android app that I have been working on that logs GPS data to my SD card in a GPX file. I currently have a main Activity that starts a Service to do all the background work. The service is kept in the foreground in the notification bar to make it the least likely thing to be killed by the OS. Currently I am requesting location updates from the service at the maximum frequency to get the most accurate route. The problem I am having is my User Interface is acting slow/strange. Correct me if I am wrong, but what I have concluded is that I have too much going on in the main thread of the app. My next thought is to try and move the service performing the acquiring and logging of data to a separate thread. I am new to Java/Android so the whole topic of interacting with separate threads is hard for me to wrap my head around. Initially in research I came across IntentServices, which are supposed to make threading easier, but from what I read these don’t seem to mix well with the Android location package because they don’t run long enough. I feel like I am running in circles with internet searches on this topic. I desperately need some guidance on how to achieve the following features for my programs service:
Separate thread from Main Thread
Fetching and storing of data must be the least likely thing to be killed by the OS and run indefinitely once started (don’t worry about battery I will have the device plugged in to power while running the app)
Eventually I will need the ability to interact with the User Interface
Thanks for any help you can offer!
this is a common problem that i have accomplished a lot on
in the launcher or main() ( what Android is calling an Activity ) you do as little as possible ( which amounts to saving the the refs they give you and maybe setting a few other things as long as you are there ) and do ^not^ drop in to a long-running activity
A Service is exactly what you need but instead of trying to pump it into a "hold on to it" state what you do is implement checks for nulls and handle as needed -- trying to "fix" a machine to make it run the way you want here actually involves rescinding you hold on the main thread and letting it go as fast as consistent with the Applicaton's general constraints.
To do this you can simply write a Service - reading everything available - then extend that service and implement Runnable then you run the constructor on that code from the Activity Constructor and do new Thead(yourClass).start(); in the onCreate() checking for Thread.isRunning() before starting it again ...
Service will have an onCompletion() call in it somewhere - it will go through an interface
All this is done in Android in something like start activity for result then you just to the UI stuff in that call or sorta figure out a way for the GUI to get called somehow at some time then check to see if Service is done an so report in the gui
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).