Topic 4 - Concurrency and Notifications
Topic 4 - Concurrency and Notifications
University of Valencia
1 Concurrent programming
2 Notifications
3 Alarms
Índice
1 Concurrent programming
2 Notifications
3 Alarms
Índice
1 Concurrent programming
Introduction
AsyncTask
Handler
Introduction
Thread class
// Stop the thread where this call has been made until the end
// the execution
public void join(){...}
Use of Thread
The call to the start() method causes the code of the run() method to
run concurrently
IncrementThread(Counter c) {
this.c = c;
}
public void run(){
for (int i=0;i<2000;i++)
c.increase();
}
}
DecrementThread(Counter c) {
this.c = c;
}
public void run(){
for (int i=0;i<2000;i++)
c.decrease();
}
}
One thread increases 2000 times and the other decreases 2000 times, the
result should be zero.
Values for different executions: -369, 286, -624, -434, -1256, 35, . . .
Topic 4, Concurrency, Notification, Alarms 10/55
Concurrent programming Introduction
When all we want is for the methods to be executed as if they were atomic
operations.
Posibilities: use Semaphore, use synchronized blocks, or declare the
methods as synchronized:
class Counter{
private double value = 0;
// Method to increase the value of the counter
public synchronized void increase() {
value++;
}
// Method to decrease the value of the counter
public synchronized void decrease(){
value--;
}
// Method to check the value of the counter
public synchronized double getValue(){
return value;
}
}
Network connections
Network connections (UDP, TCP, HTTP) must be performed in separate
threads because they have blocking operations.
UI thread
The user interface is created from a thread called main thread (or UI
thread).
From the code of a different thread we can not modify the UI. If we do
that the application finishes with an error.
Android offers different mechanisms to send code to the UI thread from
another thread.
// Method of the View class
public void post(Runnable accion)
In both cases, the code inside the run() method of the Runnable
argument is executed in the UI thread.
Índice
1 Concurrent programming
Introduction
AsyncTask
Handler
AsyncTask
AsyncTask
https://developer.android.com/reference/android/os/AsyncTask.html
AsyncTask
To inform the user of the progress made by the background task you can
periodically call publishProgress(Progress p) from the
doInBackground(Params... p) method.
That call runs the code provided in onProgressUpdate(Progress... p)
in the UI thread.
In the code of onProgressUpdate(Progress... p) the user can be
informed of the progress of the task (updating for example a TextView or
a ProgressBar).
Use of AsyncTask
A scheme of use of this class would be the following:
class Actividad extends Activity{
// Attributes of the class
AsyncTask
Once the task has been executed, it can not be executed again. It is
necessary to recreate another instance (this also happens with Thread).
Java VarArgs
In the argument of some of these methods, three dots appear after the type.
This indicates that they can receive a variable number of arguments of this
type or also an array of that type. Example:
class Example {
public static void metodo(String...p){
int nDatos = p.length;
for (int i=0;i<nDatos; i++)
System.out.print(p[i] + " ");
}
}
class SampleVarArgs{
public static void main(String[] args){
// All these calls are valid
Example.method("String1");
Example.method("String1", "String2");
Example.method("String1", "String2", "String3");
Example.method(new String [] {"String1", "String2", "String3", "String4"});
}
}
Índice
1 Concurrent programming
Introduction
AsyncTask
Handler
Handler
AsyncTask allows the execution of the code declared in its methods in two
threads: the thread that runs in the background and the UI thread.
Handler is more general as it can be used with any two threads. The use
case is to send code (in the form of Runnable) or information (in the form
of a Message) from a thread to another thread.
These tasks will be executed in the thread associated with the Handler.
The Handler can have associated the UI thread, so the code can have
access to the UI views.
The sender thread needs a reference to the Handler in order to send
Runnable or Message instances.
Handler
With the default constructor, the Handler uses the Looper of the
current thread
With a constructor that provides a Looper.
Once you have the message you can assign values to its attributes:
Índice
1 Concurrent programming
2 Notifications
3 Alarms
It is possible to specify a custom layout for the toast using the method
setView:
View layout=getLayoutInflater().inflate(R.layout.toast_layout,null);
Notifications
Notifications
In a notification you can put the following information: title, detail, small
icon, sound, Intent, etc.
To associate an Intent to the notification it is necessary to place it in a
PendingIntent.
For example if we want that when clicking on the notification an activity of
our application is opened:
Intent intent = new Intent(getApplicationContext(),Actividad.class);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
requestCode, intent, flag);
The PendingIntent stores an Intent and the context (which includes for
example the permissions).
Notifications
The second of the arguments serves to identify the component that makes
the request.
Notifications
As for the argument flag there are several possibilities (declared as static
and public constants in the class PendingIntent):
Notifications
These flags indicate what to do with the existing PendingIntent if we
already have a notification of this type:
Notifications
Notifications
Notifications
Once the notification has been created you can: delete, send, etc.
For this the class NotificationManager is used.
Context context = getApplicationContext();
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIF
...
http://developer.android.com/reference/android/content/Context.html
Índice
1 Concurrent programming
2 Notifications
3 Alarms
Alarms
Alarms
You have to take into account some recommendations when using alarms:
Alarms
A version that wakes up the CPU of the device even if it is with the
screen off (WAKEUP).
A version that waits for the device to wake up to activate the alarm.
Alarms
Therefore, the four types are (attributes declared as static in the class
AlarmManager):
Alarms
Non-repetitive alarms
Once you have an object of type AlarmManager you can use the method:
void set(int tipo, long activarMillis, PendingIntent operacion)
Non-repetitive alarms
In addition, they offer other methods that guarantee accuracy such as:
// Set a temporary window to activate the alarm
setWindow(int type, long windowStartMillis, long windowLengthMillis, PendingIntent a
Repetitive alarms
Repetitive alarms
where interval indicates the time that must elapse between activations.
void setInexactRepeating(int type, long millisStart, long millisInterval,
PendingIntent action)
where it is left to the system the decision of when to activate the alarm
within the interval (in this way the system could group the alarms not to be
activating the device).
Cancel an alarm