Android 4 Threads
Android 4 Threads
development
Vicent Selfa
Curs 2020/2021
Android Threads
http://developer.android.com
Android Threads
● Threads
● The main thread
● Using concurrency
● Without the Thread class
● With the Thread class :
■ Using post() / Runnable
● With the AsyncTask class
● An example: Calculate big prime numbers
● AsyncTask annex.
Android Threads
Some methods:
currentThread():
Returns the Thread of the caller, that is, the current Thread.
getId():
Returns the thread's identifier.
sleep(long time)
Causes the thread which sent this message to sleep for the given
interval of time (given in milliseconds).
start()
Starts the new Thread of execution.
Android Threads
The main thread
Android handles input events from one single user interface thread.
This thread is also called the main or User Interface thread.
Collects all events in a queue and processes an instance of the
Looper class.
If the programmer does not use any concurrency constructs, all code
of an Android application runs in the main thread and every
statement is executed after each other.
Android Threads
Other
threads
Android Threads
Using threads: My threads project
Android Threads
Using threads: My threads project
Android Threads
Using threads. The first project: How to block the UI?
MyThreadsActivity.java
public class MyThreadsActivity extends MainMenu {
TextView resultField;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_threads);
resultField = findViewById(R.id.textResult);
resultField.setText("Starting long calculations");
What happens if you try to click the other buttons after clicking the long calculation
without threads button? Or if you want to show the menu?
=> Rule number 1 !!!
Android Threads
Using threads. The first project: Using threads
Add a ProgressBar to your layout and initialize it into the onCreate method with
the next instructions:
ProgressBar mProgress;
mProgress = findViewById(R.id.progressBar);
mProgress.setMax(100);
mProgress.incrementProgressBy(10);
MyThreadsActivity.java
Android Threads
Using threads. Increasing the ProgressBar
Showing the progress bar
MyThreadsActivity.java
Android Threads
Using threads. Using concurrency
Showing the progress bar
Android Threads
Using threads. The AsyncTask class
AsyncTask
An asynchronous task is defined by a computation that runs on a background
thread and whose result is published on the UI thread.
Enables proper and easy use of the UI thread. This class allows to:
• perform background operations and
• publish results on the UI thread without having to manipulate threads
and/or handlers.
AsyncTask reference
AsyncTask deprecated!
Android Threads
Using threads. The AsyncTask class and the UI
Sending information to the UI using AsyncTask:
• publishProgress and onProgressUpdate
onPreExecute
doInBackground
publishProgress
onProgressUpdate
onPostExecute
Android Threads
Using threads. The AsyncTask class
AsyncTask
An asynchronous task is defined by:
3 generic types < Params, Progress, Result >
Params: the type of the parameters sent to the task upon execution.
Progress: the type of the progress units published during the background computation.
Result: the type of the result of the background computation.
Not all types are always used by an asynchronous task. To mark a type as unused, simply
use the type Void
4 steps:
• onPreExecute(): invoked on the UI thread before the task is executed.
• doInBackground (Params...): invoked on the background thread
immediately after onPreExecute() finishes executing. This step can also
use publishProgress (Progress...) to publish on the UI thread, in the
onProgressUpdate(Progress...) step.
• onProgressUpdate (Progress...), invoked on the UI thread after a call to
publishProgress(Progress...).
• onPostExecute (Result), invoked on the UI thread after the background
computation finishes. The result of the background computation is passed
to this step as a parameter.
Android Threads
Using threads. The AsyncTask class
AsyncTask
3 generic types < Params, Progress, Result >. Examples:
1.- onPreExecute:
Initial values to the progressBar
2.- doInBackground:
Call to onProgressUpdate method using the publishProgress() function
3.- onProgressUpdate:
Call to incrementProgressBy
4.- onPostExecute:
Final values to the progressBar
Android Threads
Using threads. The AsyncTask class
Showing the progress bar using AsyncTask.
● Program theAsynTask class
private class MyAsyncTask extends AsyncTask<Long, Integer, Boolean> {
int sizeInterval = 25, nTimes = 4;
protected void onPreExecute() {
// Accessing to the GUI from the Thread
resultField.setText("Starting long calculations with AsyncTask");
// Initial values for the progress bar
mProgress.setProgress(0); mProgress.setMax(100);
}
protected Boolean doInBackground(Long... params) {
for (int i = 1; i <= nTimes; i++) {
longCalculation(); publishProgress(i);
}
return true;
}
protected void onProgressUpdate(Integer... i) { // Integer…=> An array of Integer
mProgress.setProgress(sizeInterval * i[0]);
resultField.setText("Clicked on Long calculation without AsynTask." + i[0]);
}
protected void onPostExecute(Boolean result) {
// Accessing the GUI from the Thread
resultField.setText("Finished long calculations with AsyncTask");
}
public void longCalculation() {
try { Thread.currentThread().sleep(1000);
} catch (InterruptedException e) { }
}
} MyThreadsActivity.java
Android Threads
Adding publishProgress( ) and onProgressUpdate ()
Android Threads
An AsyncTask class in ANOTHER java file
Android Threads
An AsyncTask class in ANOTHER java file:
Using static variables
MyThreadsActivity.java
static TextView resultField;
static ProgressBar mProgress;
MyAsyncTaskClass.java
class MyAsyncTaskClass
extends AsyncTask<Long, Integer, Boolean> {
}
Android Threads
An AsyncTask class in ANOTHER java file
class MyAsyncTaskClass extends AsyncTask <Long, Integer, Boolean> {
int sizeInterval = 25, nTimes = 4;
protected void onPreExecute () {
// Accessing to the GUI from the Thread
MyThreadsActivity .resultField.setText( "Starting long calculations with AsyncTask" );
// Initial values for the progress bar
MyThreadsActivity .mProgress.setProgress( 0);
MyThreadsActivity .mProgress.setMax( 100);
}
protected Boolean doInBackground (Long... params) {
for (int i = 1; i <= nTimes; i++) {
longCalculation(); publishProgress(i);
}
return true ;
}
protected void onProgressUpdate (Integer... i) { // Integer…=> An array of Integer
MyThreadsActivity .mProgress.setProgress( sizeInterval * i[0]);
MyThreadsActivity .resultField.setText( "Clicked on Long calculation with AsynTask." + i[0]);
}
protected void onPostExecute (Boolean result) {
// Accessing the GUI from the Thread
MyThreadsActivity .resultField.setText( "Finished long calculations with AsyncTask" );
}
public void longCalculation () {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) { }
}
}
MyAsyncTaskClass.java
Android Threads
An Asynctask class in ANOTHER java file
Using a constructor
Android Threads
An Asynctask class in ANOTHER java file
Using a constructor
MyThreadsActivity.java
public void longCalculationWithAsyncTask3 (View view) {
MyAsyncTaskClassWithConstructor myAsyncTaskClassWithConstructor =
new MyAsyncTaskClassWithConstructor( resultField3, mProgress3);
myAsyncTaskClassWithConstructor .execute(parameter);
}
MyAsyncTaskClassWithConstructor.java
class MyAsyncTaskClassWithConstructor
extends AsyncTask<Long, Integer, Boolean> {
}
Android Threads
An Asynctask class in ANOTHER java file
Using a constructor
MyAsyncTaskClassWithConstructor.java
public class MyAsyncTaskClassWithConstructor extends AsyncTask<Long, Integer, Boolean> {
TextView myResultField; ProgressBar myProgresBar;
int sizeInterval = 25, nTimes = 4;
How much time your system needs to calculate the prime numbers?
• Add the necessary code to calculate it.
• Use different algorithms to calculate prime numbers and compare the elapsed time
Android Threads
MyAsynClass class: Example