Will thread be killed before the activity finishes in Android? - android

In Android, I have a thread that initializes a global variable. The thread starts when the activity starts. If the activity finishes before the thread initialized the global variable will the thread still run in the background to complete its job or it will be killed as the activity finishes?

The Activity finishing is part of the main execution/UI thread in android. When you spawn a new thread, and perform operations on that thread, it works as a separate entity from the main UI thread.
Hence, to answer your question - The thread will still run in the background to complete its job.
However, a word of caution. If within the run() method, you are using some objects that are part of the activity class that just got terminated, you can run into null pointer exceptions.

Related

Is the onCreate run on the main thread?

I understand that IntentServices allow running tasks on worker threads, however is the worker thread only spawn on call back to onHandleIntent?
Is the onCreate() called on the main thread and any object creation that takes place in the onCreate also takes place on the main thread?
Yes, onCreate() runs on the main thread.
If you print out the thread name in onCreate(), you get the following:
Thread[main,5,main]
However, you can spawn off background thread inside onCreate() if you don't want to block the main thread.

What happens to running AsyncTasks when the Activity changes?

While Network Operation is running in Asynctask, If user press the Back button and switch to another activity what will happen to Asynctask which is running in background?
AsyncTask Process automatically Kill by OS?
Async Task complete it's entire operation?
If you start an AsyncTask inside an Activity and you rotate the device,the Activity will be destroyed and a new instance will be created.
Similarly if user navigate to another activity,current activity will be destroyed or go in background activity stack and new activity would be in foreground.
But the AsyncTask will not die. It will go on living until it completes.
And when it completes, the AsyncTask won't update the UI of the new Activity. Indeed it updates the former instance of the activity that is not displayed anymore. This can lead to an Exception of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity.
AsyncTask is an abstract Android class which helps the Android applications to handle the Main UI thread in efficient way. AsyncTask class allows us to perform long lasting tasks/background operations and show the result on the UI thread without affecting the main thread.
1. AsyncTask processes are not automatically killed by the OS. AsyncTask processes run in the background and is responsible for finishing it's own job in any case. You can cancel your AsycnTask by calling cancel(true) method. This will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object) method is called instead of onPostExecute() after doInBackground() returns.
2. After completion of it's operation, the background thread it's working on is stopped. AsyncTask has an onPostExecute() which is called once your work is finished. This method is called after doInBackground() method completes processing. Result from doInBackground() is passed to this method.
AsyncTask will still run and try to post result on Zombie Activity. Best is to user AsyncTaskLoader.

What is the use of implementing runnable in mainactivity

Recently, I am studying a code about printer Bluetooth connection.
The program try implement runnable in the MainActivity.
Here I would like to ask 2 question.
1.How can I execute the activity as a thread when there is no other program calling run() of this activity?
2.Is there any special meaning for implementing runnable in MainActivity? Are ther any difference between implementing runnable in a class other than MainActivity?
I am not too certain what you are asking in the first question because code inside Activity will always run on the main (UI) thread by default.
To answer your second question, the MainActivity is probably implementing the Runnable interface only to define some code that can be executed on a Thread later.
For example, you can call runOnUiThread (Runnable action) from the Activity, passing MainActivity.this as the runnable parameter to execute code on the main thread.
You can also spawn a new thread with the runnable to have it run in the background or post it to a handler.
There is a sequence of callback methods that start up an activity and a sequence of callback methods that tear down an activity.
1)Created 2)Started 3)Resumed 4) Paused 5) Stopped 6)Destroyed
However, only three of these states can be static :-3)Resumed 4) Paused 5) Stopped,,,,
Resumed State(Running state):- In this state, the activity is in the foreground and the user can interact with it.
(Also sometimes referred to as the "running" state.)
here are simply two rules to Android's single thread model:
1) Do not block the UI thread
2)Do not access the Android UI toolkit from outside the UI thread

Starting a Service in a separate thread

In the Android docs, it says that a Service runs in the main thread.
What happens if I start my service in a separate thread? Does it still run on the main thread?
I am not talking about using android:process in the manifest file, but rather something like:
Thread thread = new Thread(new Runnable() {
public void run() {
// Start service
}
}).start();
Don't worry, I will not do it like that, I am just curious.
startService() starts a service in the main thread (the same as starting an Activity or any other component). In doesn't matter what thread you call startService() from.
Source: http://developer.android.com/reference/android/app/Service.html
"When a Service component is actually created, for either of these reasons, all that the system actually does is instantiate the component and call its onCreate() and any other appropriate callbacks on the main thread."
Documentation says that a Service is not even related to multithreading by default:
A service runs in the main thread of its hosting process—the service
does not create its own thread...
You can read it here: http://developer.android.com/guide/components/services.html
What your code does may be very similar to calling a View's functions from a Thread other than main thread. System doesn't let you do that. Throws an exception.
If you're asking out of curiosity and don't need any code:
First you have to understand the difference between a process and a thread (see http://docs.oracle.com/javase/tutorial/essential/concurrency/procthread.html)
All the threads in your app get triggered in the app's process by default.
The Service itself is a thread so there is no reason to launch it from a separate thread (you normally launch it from the main thread, like onCreate method and such. It's launched by default in the same process but you can specify a separate process for it by specifying processname in the declaration like so:
http://developer.android.com/guide/topics/manifest/service-element.html

Calling asynctask from runnable

Is it possible to execute an AsyncTask from Runnable? in my experience it can be done, but not safely. When my app first runs my AsyncTask runs fine from the Runnable. But when the app is moved to the background, then brought back forward I get "Can't create handler inside thread that has not called Looper.prepare()".
Here's what I'm trying to do:
I'm using MapView and invoking runOnFirstFix(Runnable) within onCreate. My Runnable calls an AsyncTask to perform a web service call which returns some data based on the location.
I move the app to the background (by tapping the home button), after some time I bring my app forward again and I'm getting the exception at the point where I'm invoking execute() on my AsyncTask.
First of all, why is runOnFirstFix being executed again? Secondly, why is it causing the exception the second time around?
I'm guessing that there is some part of the lifecycle that I don't understand.
Thanks.
It wasn't initially obvious to me that the AsyncTask needed to be called from the UI thread. So when runOnFirstFix ran the second time it was from withing a Runnable which wasn't on the UI thread. To solve the problem I simple created another Runnable inside the first to run the AsynchTask.
And the reason my runOnFirstFix seemed to be called twice was simply because I was creating a new instance of it.

Categories

Resources