0% found this document useful (0 votes)
5 views36 pages

Android 4 Threads

The document provides an overview of Android threading, detailing the main thread, concurrency, and the use of the AsyncTask class for background operations. It emphasizes the importance of not blocking the UI thread and includes code examples for implementing threading in Android applications. Additionally, it discusses the structure of AsyncTask and its lifecycle methods for managing background tasks and updating the UI.

Uploaded by

vicentselfa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views36 pages

Android 4 Threads

The document provides an overview of Android threading, detailing the main thread, concurrency, and the use of the AsyncTask class for background operations. It emphasizes the importance of not blocking the UI thread and includes code examples for implementing threading in Android applications. Additionally, it discusses the structure of AsyncTask and its lifecycle methods for managing background tasks and updating the UI.

Uploaded by

vicentselfa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Mobile

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

Interesting websitesto look:


• Threads
• AsyncTask
• Processes and threads
Android Threads
Threads

A Thread is a concurrent unit of execution. It has its own call stack


for methods being invoked, their arguments and local variables. Each
application has at least one thread running when it is started, the
main thread, in the main ThreadGroup. The runtime keeps its own
threads in the system thread group.

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

Why using concurrency?


If you perform a long-lasting operation, for example accessing data
from the Internet or doing complex calculations, the application
would be blocked until the corresponding operation has finished.

The two rules to Android's single


thread model:
The UI
1.- Do not block the UI thread!!!
thread
2.- Do not access the Android
UI toolkit from outside the UI
thread!!!

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");

public void longCalculationWithoutThreads(View view)


{// TODO }
public void longCalculationWithThreads(View view)
{// TODO }
public void longCalculationWithAsyncTask(View view)
{// TODO }
}
Android Threads
Using threads. The first project: How to block the UI?

public void longCalculationWithoutThreads(View view) {


resultField.setText("Clicked on Long calculation without threads." );
try {
Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {}
// Showing the result into the UI thread
resultField.setText("Finished long calculations");
}
MyThreadsActivity.java

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

public void longCalculationWithThreads(View view) {


resultField.setText("Clicked on Long calculation with threads.");
( new Thread() {
public void run() {
try { Thread.currentThread().sleep(4000);
} catch (InterruptedException e) {}
// Try to uncomment the next line. What happens?
//resultField.setText("Finished long calculations with threads");
}
} ).start();
}
MyThreadsActivity.java

What happens if you try to click the other buttons?


• Rule number 1 OK!!!
And if you uncomment the message line?
• Nothing happens with the current version of Android, no problem appears … but it
is recommended:
○ Do not access the Android UI toolkit from outside the UI thread
Android Threads
Using threads. Improving the layout

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

public void longCalculationWithThreads(View view) {


Log.d("AsyncTAsk", "Into longCalculationWithThreads ");
resultField.setText("Clicked on Long calculation with threads.");
( new Thread() {
public void run() {
for (int i = 1; i <= 4; i++) { // To show the progress bar
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) { }
mProgress.incrementProgressBy(25);
resultField.setText("Clicked on Long calculation without threads."
+1);
}
resultField.setText("Finished long calculations with threads");
mProgress.setProgress(0); // reset the progress bar
}
} ).start();
}

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

UI thread AsyncTask thread

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:

Maximum Prime numbers in an Sum of the first N


Common Divider: Interval (x0, x1) natural numbers
Params: X, Y Params: x0, x1 Params: N
Progress: Void Progress: The prime Progress: 1, 2, 3, …
Result: mcd (X,Y) numbers Result: The total sum
Result: True
MCD ( 12, 21) = 3
Prime numbers in
(3, 20):
3, 5, 7, 11, 13, 17
Android Threads
Using threads. The AsyncTask class
Android Threads
Using threads. The AsyncTask class
Showing the progress bar using AsyncTask.
● Create an AsyncTask object
● Execute it.

public void longCalculationWithAsyncTask (View view) {


resultField .setText("Clicked on Long calculation with AsyncTask." );
Long parameter = (long) 4000;
MyAsyncTask myAsyncTask = new MyAsyncTask();
myAsyncTask .execute(parameter);
}
MyThreadsActivity.java
Android Threads
Adding publishProgress( ) and onProgressUpdate ()

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;

public void longCalculationWithAsyncTask2 (View view) {


resultField.setText("Clicked on Long calculation with AsyncTask in a new class."
);
Long parameter = (long) 4000;
MyAsyncTaskClass myAsyncTaskClass = new MyAsyncTaskClass();
myAsyncTaskClass .execute(parameter);
}

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) {

resultField3 = findViewById( R.id.textResult);


resultField3.setText("Click on a button..." );
mProgress3 = findViewById( R.id.progressBar);
mProgress3.setMax(100);
resultField.setText(
"Clicked on Long calculation with AsyncTask in a new class using a
constructor." );
Long parameter = (long) 4000;

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;

public MyAsyncTaskClassWithConstructor (TextView textView, ProgressBar progressBar) {


myResultField = textView; myProgresBar = progressBar;
}
protected void onPreExecute() {
// Accessing to the GUI from the Thread
myResultField.setText("Starting long calculations with AsyncTask");
// Initial values for the progress bar
myProgresBar.setProgress(0); myProgresBar.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
myProgresBar.setProgress(sizeInterval * i[0]);
myResultField.setText("Clicked on Long calculation with AsynTask."+ i[0]);
}
protected void onPostExecute(Boolean result) {
// Accessing the GUI from the Thread
myResultField.setText("Finished long calculations with AsyncTask");
}
public void longCalculation() {
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) { }
}
}
Android Threads
An AsyncTask class in ANOTHER java file
Sending variables to the AsyncTask class: Sending and array of values.

public void longCalculationWithAsynTask(View v) {


Long value0 = Long.valueOf(1000);
Long value1 = Long.valueOf(2000);
Long value2 = Long.valueOf(3000);
MyAsyncTask myAsyncTask = new MyAsyncTask
(myVariable); (value0, value1, value2);
} myAsyncTask.execute
MyThreadsActivity.java

public class MyAsyncTaskClassWithConstructor


extends AsyncTask<Long, Integer, Boolean> {
@Override
protected Boolean doInBackground (Long... params) { //
// Here the code of the method
// value0 => params[0]; value1 => params[1]; value2 => params[2];
}
MyAsyncTaskClassWithConstructor.java
Android Threads
Computing prime numbers: The layout
Android Threads
Computing prime numbers: The control
Different functions to calculate prime numbers.
public boolean isPrimeNumber(long n) { public boolean isPrimeNumber (long n) {
int contador = 0; int contador = 2; boolean primo=true;
boolean isPrime; while ((primo) &&
for(int i = 1; i <= n; i++){ (contador!=numero)){
if((n % i) == 0) { contador++; } if (numero % contador == 0)
} primo = false; contador++;
if(contador <= 2) isPrime = true; }
else isPrime = false; return primo;
return isPrime; } The bad
} The worst!!!

public boolean isPrimeNumber (long n){ public boolean isPrimeNumber (long n) {


boolean isPrime = true; boolean isPrime = true;
for (int i = 2; i <= n/2; ++i) { if (n%2==0)isPrime = false;
if (n % i == 0) { else {
isPrime = false; break; long factor=3;
} double limit = Math.sqrt(n)+0.0001;
} while (factor < limit) {
return isPrime; if (n%factor==0) {
} isPrime = false; break;
The good }
factor+=2;
Exercises: }
• Discus what are the differences between return isPrime;
the previous algorithms } The best
• Long or BigInteger? What is the best
option?
Android Threads
MyAsynClass class: Example

Create a new activity to calculate the prime numbers into an interval

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

Do the two previous activities but using AsyncTask classes.


Android Threads
MyAsynClass class: Annex
In the theory what is the best option?
1. An only ONE AsyncTask with a loop for the interval of prime numbers …
2. Or a loop including a LOT of AsyncTask, one per each number of the interval?

// Option 1.- This is pseudocode!


Long begin, end;
// Only ONE AsyncTask call
myAsyncTask.execute (begin, end);
// The AsyncTask class
@Override
protected Boolean doInBackground (Long... n){
for (long i = n[0]; i <= n[1]; i++ ) {// Call the function isPrimeNumber (i);}
return true; // Means that we have finish
}

// Option 2.- This is pseudocode!


for (long i = begin; i <= end; i++ ) {
// A lot of calls to the AsyncTask class
myAsyncTask.execute (i);
}
// The AsyncTask class
@Override
protected Boolean doInBackground (Long... n){ return isPrimeNumber (n); }

But: You can read here that:


The task can be executed only once (an exception will be thrown if a second
execution is attempted).
So, in the practice, only the option 1 is valid.

You might also like