4 - xử lý Đa tiến trình và dịch vụ
TRANSCRIPT
-
8/11/2019 4 - X L a Tin Trnh V Dch V
1/147
DONG NAI UNIVERSITY OF TECHNOLOGY
1
5. Webservice .Net
4. Android Services
3. Broadcast Receiver
2. Intent filter
1. Multi - Threading
-
8/11/2019 4 - X L a Tin Trnh V Dch V
2/147
DONG NAI UNIVERSITY OF TECHNOLOGY
2
1. Multi - Threading
1.1 Introduction
1.2 Handler class
1.3 AsyncTask class
-
8/11/2019 4 - X L a Tin Trnh V Dch V
3/147
DONG NAI UNIVERSITY OF TECHNOLOGY
3
1.1 Introduction
Threads
Androids threads run in a manner similar to common
Java threads
A Thread is a concurrent unit of execution.
not executing in order
has its own call stack for methods being invoked, their
arguments and local variables.
Each virtual machine instance has at least one main
Thread running when it is started;The application might decide to launch additional Threads
for specific purposes.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
4/147
DONG NAI UNIVERSITY OF TECHNOLOGY
4
1.1 Introduction
Multi- Threading
-
8/11/2019 4 - X L a Tin Trnh V Dch V
5/147
DONG NAI UNIVERSITY OF TECHNOLOGY
5
1.1 Introduction
Multi- Threading
Threads in the same VM interact and synchronize by the
use of shared objects and monitors associated with
these objects.
There are basically two main ways of having a Threadexecute application code.
1.Create a new class that extends Thread and override its
run() method.
2.Create a new Thread instance passing to it a Runnable
object.
In both cases, the start() method must be called to
actually execute the new Thread.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
6/147
DONG NAI UNIVERSITY OF TECHNOLOGY
6
1.1 Introduction
Advantages of Multi- Threading
Threads share the process' resources but are able to
execute independently.
Applications responsibilities can be separated main
thread runs UI, and slow tasks are sent to background
threads.
Threading provides an useful abstraction of concurrent
execution.
Particularly useful in the case of a single process that
spawns multiple threads on top of a multiprocessor
system. In this case real parallelism is achieved.Consequently, a multithreaded program operates faster on
computer systems that have multiple CPUs.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
7/147
DONG NAI UNIVERSITY OF TECHNOLOGY
7
1.1 Introduction
Disadvantages of Multi- Threading
Code :more complex
Need to detect, avoid, resolve deadlocks
Threads not executing in orderRunnable v.s Thread?
What different?
Deadlock and Atomic type
-
8/11/2019 4 - X L a Tin Trnh V Dch V
8/147
DONG NAI UNIVERSITY OF TECHNOLOGY
8
1.2 Handler class
An application may involve a time-consuming operation,
however we want the UI to be responsive to the user. Android
offers two ways for dealing with this scenario:
Do expensive operations in a background service, using
notifications to inform users about next stepDo the slow work in a background thread. Interaction
between Android threads is accomplished using (a)
Handler objects and (b) posting Runnable objects to the
main view.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
9/147
DONG NAI UNIVERSITY OF TECHNOLOGY
9
1.2 Handler class
When a process is created for your application, its main
thread is dedicated to running a message queue that takes
care of managing the top-level application objects (activities,
intent receivers, etc) and any windows they create.
You can create your own secondary threads, andcommunicate back with the main application thread through
a Handler.
When you create a new Handler, it is bound to the message
queue of the thread that is creating it -- from that point on, itwill deliver messages and runnables to that message queue
and execute them as they come out of the message queue.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
10/147
DONG NAI UNIVERSITY OF TECHNOLOGY
10
1.2 Handler class
There are two main uses for a Handler:
(1)to schedule messages and runnables to be executed assome point in the future; and
(2)to enqueue an action to be performed on another thread
-
8/11/2019 4 - X L a Tin Trnh V Dch V
11/147
DONG NAI UNIVERSITY OF TECHNOLOGY
11
1.2 Handler class
Threads and UI Warning
Background threads are not allowed to interact withthe UI.
Only the main process can access the (main)
activitys view.
(Global) class variables can be seen and updated inthe threads
-
8/11/2019 4 - X L a Tin Trnh V Dch V
12/147
DONG NAI UNIVERSITY OF TECHNOLOGY
12
1.2 Handler class
Handlers MessageQueue
A secondary thread that wants to communicate with the main
thread must request a message token using the
obtainMessage() method.
Once obtained, the background thread can fill data into the
message token and attach it to the Handlers message queue
using the sendMessage() method.
The Handler uses the handleMessage() method to
continuously attend new messages arriving to the main thread.A message extracted from the process queue can either
return some data to the main process or request the execution
of runnable objects through thepost() method.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
13/147
DONG NAI UNIVERSITY OF TECHNOLOGY
13
1.2 Handler class
Handlers MessageQueue
-
8/11/2019 4 - X L a Tin Trnh V Dch V
14/147
DONG NAI UNIVERSITY OF TECHNOLOGY
14
1.2 Handler class
Using Messages
Main Thread Background Thread
-
8/11/2019 4 - X L a Tin Trnh V Dch V
15/147
DONG NAI UNIVERSITY OF TECHNOLOGY
15
1.2 Handler class
-
8/11/2019 4 - X L a Tin Trnh V Dch V
16/147
DONG NAI UNIVERSITY OF TECHNOLOGY
16
1.2 Handler class
To send a Message to a Handler, the thread must first invoke
obtainMessage() to get the Message object out of the pool.
There are a few forms of obtainMessage(), allowing you to
just create an empty Message object, or messages holdingarguments
Example
// thread 1 produces some local dataString localData = Greeting from thread 1;
// thread 1 requests a message & adds localData to it
Message mgs = myHandler.obtainMessage (1, localData);
Messages
-
8/11/2019 4 - X L a Tin Trnh V Dch V
17/147
DONG NAI UNIVERSITY OF TECHNOLOGY
17
1.2 Handler class
sendMessage Method
You deliver the message using one of the sendMessage...()
family of methods, such as
sendMessage() puts the message at the end of the
queue immediately
sendMessageAtFrontOfQueue() puts the message atthe front of the queue immediately (versus the back, as is
the default), so your message takes priority over all others
sendMessageAtTime() puts the message on the queue
at the stated time, expressed in the form of millisecondsbased on system uptime (SystemClock.uptimeMillis())
sendMessageDelayed() puts the message on the
queue after a delay, expressed in milliseconds
-
8/11/2019 4 - X L a Tin Trnh V Dch V
18/147
DONG NAI UNIVERSITY OF TECHNOLOGY
18
1.2 Handler class
Processing Messages
To process messages sent by the background
threads, your Handler needs to implement the listener
handleMessage( . . . )
which will be called with each message that appearson the message queue.
There, the handler can update the UI as needed.
However, it should still do that work quickly, as other
UI work is suspended until the Handler is done.
-
8/11/2019 4 - X L a Tin Trnh V Dch V
19/147
DONG NAI UNIVERSITY OF TECHNOLOGY
19
1.2 Handler class
Examples
Using Message
XML Layout
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
20/147
DONG NAI UNIVERSITY OF TECHNOLOGY
20
1.2 Handler class Coding
msg get from sendMessage in
background thread
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
21/147
DONG NAI UNIVERSITY OF TECHNOLOGY
21
1.2 Handler class Coding
msg send to main Thread,
process in handleMessage
msg get from main Thread
We could use msg.arg1, msg.arg2, msg.obj (store Object),
msg.what to process message
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
22/147
DONG NAI UNIVERSITY OF TECHNOLOGY
22
1.2 Handler class
Examplesusing post
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
23/147
DONG NAI UNIVERSITY OF TECHNOLOGY
23
1.2 Handler class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
24/147
DONG NAI UNIVERSITY OF TECHNOLOGY
24
1.2 Handler class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
25/147
DONG NAI UNIVERSITY OF TECHNOLOGY
25
1.2 Handler class
Exercise: Draw Button at runtime on the View as below
Whe click on the Draw Button::
- After 1 second, application will draw1 button. The number of button is
entered in the EditText.
- Must use MultiThreading (Messageor post)
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
26/147
DONG NAI UNIVERSITY OF TECHNOLOGY
26
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
27/147
DONG NAI UNIVERSITY OF TECHNOLOGY
27
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
28/147
DONG NAI UNIVERSITY OF TECHNOLOGY
28
1.3 AsyncTask class
Start by execute method
AsyncTask 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.
An asynchronous task is defined by a computation that
runs on a background thread and whose result is published
on the UI thread.
An asynchronous task is defined by
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
29/147
DONG NAI UNIVERSITY OF TECHNOLOGY
29
1.3 AsyncTask class
AsyncTask
Not all types are always used by an asynchronous task.To mark a type as unused, simply use the type Void
Note: Syntax String ... indicates (Varargs) array of
String values, similar to String[]
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
30/147
DONG NAI UNIVERSITY OF TECHNOLOGY
30
1.3 AsyncTask class AsyncTask's methods
onPreExecute(), invoked on the UI thread immediately after the task is executed.
This step is normally used to setup the task, for instance by showing a progress
bar in the user interface.
doInBackground(Params...), invoked on the background thread after
onPreExecute() finishes executing: perform long time background computation.
The parameters of the asynchronous task are passed to this step. The result of the
computation must be returned by this step and will be passed back to the last step.
This step can also usepubl ishProgress
(Progress...) to publish one or more unitsof progress. These values are published on the UI thread, in the
onProgressUpdate(Progress...) step.
onProgressUpdate(Progress...), invoked on the UI thread after a call to
publ ishProgress(Progress...). The timing of the execution is undefined. This
method is used to display any form of progress in the user interface while the
background computation is still executing. For instance, it can be used to animatea progress bar or show logs in a text field.
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.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
31/147
31
1.3 AsyncTask class
Examples : combine
AsyncTask and Handler class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
32/147
32
1.3 AsyncTask class
Examples : combine
AsyncTask and Handler class
Random Number: Auto draw button
with random number in the left side
List prime: Auto draw list Prime butto
when the Random number is finished
in the Right side
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
33/147
33
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
34/147
34
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
35/147
35
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
36/147
36
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
37/147
37
1.3 AsyncTask class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
38/147
38
2. Intent filter
INTENTS
An intent is an abstract description of an operation to beperformed.
Its most significant use is in the launching of activities.
The primary pieces of information in an intent are:
act ion & data.
Parts of a Typical Intent
http://developer.android.com/reference/android/content/Intent.html
DONG NAI UNIVERSITY OF TECHNOLOGY
http://developer.android.com/reference/android/content/Intent.htmlhttp://developer.android.com/reference/android/content/Intent.htmlhttp://developer.android.com/reference/android/content/Intent.htmlhttp://developer.android.com/reference/android/content/Intent.html -
8/11/2019 4 - X L a Tin Trnh V Dch V
39/147
39
2. Intent filter
The intent resolution mechanism basically revolves around
matching an Intent against all of the descriptions in the installed application packages.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
40/147
40
2. Intent filter
intent filters that specify the
android.intent.action.MAIN action andandroid.intent.category.LAUNCHER Category:
It then displays the icons and labels of those activities in
the launcher
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
41/147
41
2. Intent filter
Intent Resolution: example
Assume the user has installed a Fancy SMS applicationto (perhaps) replace the standard HUMBLE SMS app
originally included in Android.
Upon the arrival of the implicit Intent, Android will
(somehow) tell the user:You have got a new textmessage. I have a FANCY and
a HUMBLE SMS application which one you want me to
execute? Make it a default?
Choosing candidates: For an activity to be eligible for
execution it must:1. Support the specified action
2. Support the indicated MIME type (if supplied)
3. Support all of the categories named in the intent.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
42/147
42
2. Intent filter
Common case:
For example, a element like the following tellsAndroid that the component can get video data from the
network and display it:
Usage examle
Consider what the browser application does when the
user follows a link on a web page.
It first tries to display the data (as it could if the link was
to an HTML page). If it can't display the data, it puts
together an implicit intent with the scheme and data typeand tries to start an activity that can do the job. If there
are no takers, it asks the download manager to download
the data.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
43/147
43
2. Intent filter
Common case:
The example below tells Android that the component can
get image data from a content provider and display it:
Since most available data is dispensed by content
providers, filters that specify a data type but not a URI are
perhaps the most common.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
44/147
44
2. Intent filter
Example:
Share pictureimg.setImageURI((Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM));
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
45/147
45
3. Broadcast Receiver
Broadcast Receiver Lifecycle
A Broadcast Receiver is an application class that listensfor Intents that are broadcast, rather than being sent to a
single target application/activity.
The system delivers a broadcast Intent to all
interested broadcast receivers, which handle theIntent sequential ly.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
46/147
46
3. Broadcast Receiver
A broadcast receiver has a single callback method:void onReceive(Context curContext,
Intent broadcastMsg)
1.When a broadcast message arrives for the receiver,
Android calls its onReceive()method and passes it the Intentobject containing the message.
2.The broadcast receiver is considered to be active only
while it is executing this method.
3.When onReceive() returns, it is inactive.
Broadcast Receiver Lifecycle
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
47/147
47
3. Broadcast Receiver
Registering a Broadcast Receiver
1. You can either dynamically register an instance of thisclass with Context.registerReceiver()
2. or statically publish an implementation through the
tag in your AndroidManifest.xml.
Manifestthe application defines a BroadcastReceiver as an
independent class, it must include a clause
identifying the component. In addition an
entry is needed to declare the actual filter the serviceand the receiver use.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
48/147
48
3. Broadcast Receiver
Manifest
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
49/147
49
3. Broadcast Receiver
Types of Broadcasts
There are two major classes of broadcasts that can bereceived:
1.Normal broadcasts(sent with
Context.sendBroadcast) are completely asynchronous.
All receivers of the broadcast are run in an undefinedorder, often at the same time.
2.Ordered broadcasts(sent with
Context.sendOrderedBroadcast) are delivered to one
receiver at a time.
The order receivers run in can be controlled with the
android:priority attribute of the matching intent-filter;
abortBroadcast()
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
50/147
50
3. Broadcast Receiver
Standard Broadcast given by the platform
AIRPLANE_MODE ACTION_TIME_TICK
ACTION_TIME_CHANGED
ACTION_TIMEZONE_CHANGED
ACTION_BOOT_COMPLETED
ACTION_PACKAGE_ADDED ACTION_PACKAGE_CHANGED
ACTION_PACKAGE_REMOVED
ACTION_PACKAGE_RESTARTED
ACTION_PACKAGE_DATA_CLEARED
ACTION_UID_REMOVED ACTION_BATTERY_CHANGED
ACTION_POWER_CONNECTED
ACTION_POWER_DISCONNECTED
ACTION_SHUTDOWN
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
51/147
51
3. Broadcast Receiver
Sender
Send broadcastAction
Receiver
Any activity that intends to respond to broadcasts has to
have class extend the android.content.BroadcastReceiver
and implement the single method onReceive()
Manifest file
Action
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
52/147
52
3. Broadcast Receiver
Register BroadCast Receiver by coding
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
53/147
53
3. Broadcast Receiver
Register BroadCast Receiver by Manifest XML
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
54/147
54
3. Broadcast Receiver
Example read SMS by Broadcast Receiver
Automatic show information when
the phone receives any SMS message
(even this application is destroy)
Click Read SMS to read all inbox sms
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
55/147
55
3. Broadcast Receiver
Layout XML
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
56/147
56
3. Broadcast Receiver MySmsReceiver class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
57/147
57
3. Broadcast Receiver MainActivity class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
58/147
58
3. Broadcast Receiver MainActivity class
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
59/147
59
3. Broadcast Receiver Manifest XML
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
60/147
60
3. Broadcast Receiver Manifest XML
MySmsReceiveris as a services when register in Manifest XML.
When .apkis installed in the Phone, it becomes a Services. Soyou dont need to launch the application but it still receives
broadcast when any SMS come in.
SMS come in
Automatic go to onReceive
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
61/147
61
4. Android Services
1.1 Services
1.2 PendingIntent
1.3 AlarmManager
1.4 NotificationManager
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
62/147
62
1.1 Services
A Service is an application component that runs in the
background, not interacting with the user, for anindefinite period of time.
Run in the main thread of their hosting process. This
means that
Each service class must have a corresponding declaration in its package's
AndroidManifest.xml.
Services can be started with Context.startService() and
Context.bindService().
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
63/147
63
1.1 Services
singleton
Multiple calls to Context.startService() do not nest(though they do result in multiple corresponding calls to
the onStart() method of the Service class)
Only one stopService( )call is needed to stop the
service, no matter how many times startService() was
called.
A service can be started and allowed to run until someone
stops it or it stops itself.
stopped when: Context.stopService() or stopSelf() is
called.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
64/147
64
1.1 Services
Service Life Cycle
Like activityhas lifecycle methods to monitor
changes in its state.
fewer than the activity methods
1.void onCreate()2.void onStart(Intentintent)
3.void onDestroy()
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
65/147
65
1.1 Services
Service Life Cycle
The entire lifetime of a service happens between thetime onCreate() is called and the time onDestroy()
returns.
Like an activity, a service does its initial setup in
onCreate(), and releases all remaining resources inonDestroy().
For example, a music playback service could create the
thread where the music will be played in onCreate(), and
then stop the thread in onDestroy().
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
66/147
66
1.1 Services
The manifest of applications using Android Services
must include:1.A entry for each service used in the
application.
2.If the application defines a BroadcastReceiveras
an independent class, it must include a clause identifying the component. In addition an
entry is needed to declare the actual
filter the service and the receiver use.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
67/147
67
1.1 Services
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
68/147
68
1.1 Services
Example 1. A very Simple Service
The main application starts a service. The service printslines on the DDMS LogCat until the main activity stops
the service. No IPC occurs in the example.
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
69/147
69
1.1 Services Example 1. cont
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
70/147
70
1.1 Services Example 1. cont
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
71/147
71
1.1 Services
Communication with service
BroadcastBinder
Messenger
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
72/147
72
1.1 Services Using Broadcast
Assume main activity MyService3Driverwants to
interact with a service called MyService3. The mainactivity is responsible for the following tasks:
DONG NAI UNIVERSITY OF TECHNOLOGY
U i B d
-
8/11/2019 4 - X L a Tin Trnh V Dch V
73/147
73
1.1 Services Using Broadcast
DONG NAI UNIVERSITY OF TECHNOLOGY
i U i B d t
-
8/11/2019 4 - X L a Tin Trnh V Dch V
74/147
74
1.1 Services Using Broadcast
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 S i E l 2 B d t
-
8/11/2019 4 - X L a Tin Trnh V Dch V
75/147
75
1.1 Services Example 2 - Broadcast
1.The main activity starts the service and registers a
receiver.2.The service is slow, therefore it runs in a parallel thread its
time consuming task.
3.When done with a computing cycle, the service adds a
message to an intent.
4.The intent is broadcasted using the filter:
matos.action.GOSERVICE3.
5.A BroadcastReceiver(defined inside the main Activity) uses
the previous filter and catches the message (displays the
contents on the main UI ).6.At some point the main activity stops the service and
finishes executing
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 S i E l 2 B d t
-
8/11/2019 4 - X L a Tin Trnh V Dch V
76/147
76
1.1 Services Example 2 - Broadcast
XML Layout
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 S i E l 2 B d t
-
8/11/2019 4 - X L a Tin Trnh V Dch V
77/147
77
1.1 Services Example 2 - Broadcast
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 S i E l 2 B d t
-
8/11/2019 4 - X L a Tin Trnh V Dch V
78/147
78
1.1 Services Example 2 - Broadcast
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 S i E l 2 B d t
-
8/11/2019 4 - X L a Tin Trnh V Dch V
79/147
79
1.1 Services Example 2 - Broadcast
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 S i Binding ser ice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
80/147
80
1.1 Services Binding service
local binding
sync from activity to serviceActivity get services instance
Throught ServiceConnection (Activity) + Binder (Service)
Using bindService method
unbindService: for stop service
Take yourself
Click here to get Example
DONG NAI UNIVERSITY OF TECHNOLOGY
1 1 Services Using Messager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
81/147
81
1.1 Services Using Messager
Take yourself
Extends Handler for activity and service
Take Messenger for activity and serviceActivity get Messenger from service in method
onServiceConnected
Send message between activity and service from
messengerMessenger.Send(Message)
Process message in handleMessage(Message msg)Define constant
Click here to get Example
DONG NAI UNIVERSITY OF TECHNOLOGY
1 2 PendingIntent
-
8/11/2019 4 - X L a Tin Trnh V Dch V
82/147
82
1.2 PendingIntent
A PendingIntent is a token that you give to another
application (e.g. Notification Manager, Alarm Manageror other 3rd party applications), which allows this other
application to use the permissions of your application to
execute a predefined piece of code.
To perform a broadcast via a pending intent so get aPendingIntent via PendingIntent.getBroadcast(). To
perform an activity via an pending intent you receive the
activity via PendingIntent.getActivity().
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
83/147
83
1.3 AlarmManager
system services.
AlarmManager am = (AlarmManager)
getSystemService(Context.ALARM_SERVICE);
allow you to schedule your application to be run at some
point in the future.
When an alarm goes off
PendingIntent will be called.To set an absolute time for event
if the device is on stand-by, use the RTC_WAKEUP type.
one shot or repeating
alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),pendingIntent);
alarmManager.setRepeating(type, triggerAtTime, interval,
pendingIntent))
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
84/147
84
1.3 AlarmManager
Example 1: PendingIntent.getBroadcast
MyBroadcastReceiver
Open new instance of MainActivity
Old MainActivity
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager Example 1: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
85/147
85
1.3 AlarmManager Example 1: cont
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager Example 1: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
86/147
86
1.3 AlarmManager Example 1: cont
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager Example 1: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
87/147
87
1.3 AlarmManager Example 1: cont
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager Example 1: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
88/147
88
1.3 AlarmManager Example 1: cont
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
89/147
89
1.3 AlarmManager
Example 2: PendingIntent.getService
DONG NAI UNIVERSITY OF TECHNOLOGY
1 3 AlarmManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
90/147
90
1.3 AlarmManager
Example 2: PendingIntent.getService
DONG NAI UNIVERSITY OF TECHNOLOGY
1 4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
91/147
91
1.4 NotificationManager
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
92/147
92
1.4 NotificationManager
System service
alerting a user about an event
Notification on Android can be done in any of the following ways:
Status Bar Notification
Vibrate
Flash lights
Play a soundWe need:
Notification
defines the properties of the status bar notification like the
icon to display, the test to display when the notification first
appears on the status bar and the time to displayNotificationManager
android system service that executes and manages all
notifications.
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
93/147
93
1.4 NotificationManager
NotificationManager
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE)
Create a new Notification object with an icon, a title and the
time (probably System.currentTimeMillis()) Set some flags
notification.defaults |= Notification.DEFAULT_SOUND;notification.defaults |= Notification.DEFAULT_VIBRATE;
Use setLatestEventInfo method to set another PendingIntent
into the notification.
The Activity in this intent will be called when the user clicks
the notification.
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
94/147
94
1.4 NotificationManager
Step 1: Procure a handle to the NotificationManager:
private NotificationManager mNotificationManager;mNotificationManager =
(NotificationManager)getSystemService(NOTIFICATIO
N_SERVICE);Step 2: Create a notification object along with
properties to display on the status bar final Notification
notifyDetails = new
Notification(R.drawable.android,"New Alert, Click
Me!",System.currentTimeMillis());
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
95/147
95
1.4 NotificationManager
Step 3:Add the details that need to get displayed when the
user clicks on the notification.
Context context= getApplicationContext();
CharSequence contentTitle= "Notification Details...";
CharSequence contentText= "Browse Android Official Site by clicking me";
Intent notifyIntent= new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.android.com"));
PendingIntent pintent=
PendingIntent.getActivity(SimpleNotification.this, 0, notifyIntent,
Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo
(context, contentTitle, contentText, pintent);
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
96/147
96
1.4 NotificationManager
Step 4: Now the stage is set. Notify.
mNotificationManager.notify
(SIMPLE_NOTFICATION_ID, notifyDetails);
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager
-
8/11/2019 4 - X L a Tin Trnh V Dch V
97/147
97
1.4 NotificationManager
Example : Show notification
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager Example : cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
98/147
98
g Example : cont
DONG NAI UNIVERSITY OF TECHNOLOGY
1.4 NotificationManager Example : cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
99/147
99
g Example : cont
DONG NAI UNIVERSITY OF TECHNOLOGY
5. Webservice .Net
-
8/11/2019 4 - X L a Tin Trnh V Dch V
100/147
100
5.1 Introduction Webservice
5.2 How to create .Net Webservice
5.3 How to config IIS
5.4 KSOAP API
5.5 Android to .Net Webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Introduction Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
101/147
101
Support machine-to-machine collaboration.
They can be described, published, located, andinvoked over a data network.
Web services are used to implement the notion of a
service-oriented architecture (SOA).
SOA app l icat ions are independent of speci f ic
programm ing languages or operat ing sys tems.
Web services rely on existing transport technologies,
such as HTTP, and XML, for invoking theimplementation.
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Introduction Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
102/147
102
The interface describing the format of services can be
done using the Web Services Description Language(WSDL). According to W3C there are two major types
of web servicesREST-compliant which use XML to represent its Web
resources, and offers a "stateless" set of operations; and
Arbitrary solutions, in which the service may expose a
heterogeneous set of operations.
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Introduction Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
103/147
103
Two widely used architectures supporting Web
services areRepresentational State Transfer (REST) Closely tie to
the HTTP protocol by associating its operation to the
common GET, POST, PUT, DELETE for HTTP.
Remote Procedure Call (RPC). Web services are directly
implemented as language-specific functions or methodcalls. In this category we find
1.Object Management Group's (OMG) Common
Object Request Broker Architecture (CORBA),
2.Microsoft's Distributed Component Object Model(DCOM) and
3.Sun Microsystems's Java/Remote Method
Invocation (RMI).
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Introduction Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
104/147
104
IIS webserver (RPC discrete function oriented approach)
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Introduction Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
105/147
105
Services are passive server-side pieces of code
waiting for incoming messages to do some work.Clients initiate the interaction by sending a message to
server-services requesting action.
Services expose one or more endpoints wheremessages can be sent. Each endpoint consists of
address (where to send messages)
binding (how to send messages )
contract (what messages contain)
Clients can use WSDL to know this information before
accessing a service.
DONG NAI UNIVERSITY OF TECHNOLOGY
5.1 Introduction Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
106/147
106
Windows Communication Foundation (WCF) uses the
information found in the service contract to performdispatching and serialization.
Dispatching is the process of deciding which method
to call for an incoming SOAP message.
Serialization is the process of mapping between the
data found in a SOAP message and the corresponding
.NET objects used in the method
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
107/147
107
1. Create a database in SQL Server with name dbProductManager
The Table Structer as below:
2. Computer Server will support some services:
- Get number of catalog
- Get list Catalog
- Get list product by Catalog id3. Android application will connect to the computer Server and
get information via service method (The Android Mobile will
connect to Laptop by Wirelessmust Win 7, Win 8)
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
108/147
108
1- Create Webservice project with name MyProductServiceas
below:
-
8/11/2019 4 - X L a Tin Trnh V Dch V
109/147
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
110/147
110
3- Write coding :
For Product table
For Catalog table
Must use Serializable
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice 3- Write coding :
-
8/11/2019 4 - X L a Tin Trnh V Dch V
111/147
111
For connection
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice 3- Write coding :
-
8/11/2019 4 - X L a Tin Trnh V Dch V
112/147
112
For connection
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice 3- Write coding :
-
8/11/2019 4 - X L a Tin Trnh V Dch V
113/147
113
For Webservice
Namespace http://tranduythanh.com/will use in Android Coding
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice 3- Write coding :
http://tranduythanh.com/http://tranduythanh.com/ -
8/11/2019 4 - X L a Tin Trnh V Dch V
114/147
114
For Webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.2 How to create .Net Webservice 3- Write coding :
-
8/11/2019 4 - X L a Tin Trnh V Dch V
115/147
115
For Webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
116/147
116
1. In control Panel/ Click Turn Windows features on or off
2. Enable Internet Information
Service (with sub configuration)
then click OK
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
117/147
117
3. Administrator tools: choose IIS
4. Add application:
- Right click on Default Website
Then click Add Application
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
118/147
118
4. Add application:
Type Alias name and choose Physical path, then click OK to create
-
8/11/2019 4 - X L a Tin Trnh V Dch V
119/147
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
120/147
120
5. Config directory Browsing
Double click onDirectory Browsing
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
121/147
121
5. Config directory Browsing
Click Enable
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
122/147
122
6. Test IIS
Type localhost on Address bar then press enter
The figureIt is
ok for IIS
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
123/147
123
6. Test IIS: Now, test your ProductWebService in IIS. You could
use localhost or get your computer IP.
Click to Test this method
192.168.3.102: My computer IP
productwebservice: alias that I defined in IIS
Productwebservice.asmx: webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.3 How to config IIS
-
8/11/2019 4 - X L a Tin Trnh V Dch V
124/147
124
6. Test IIS
The result are OK
DONG NAI UNIVERSITY OF TECHNOLOGY
5.4 KSOAP API
-
8/11/2019 4 - X L a Tin Trnh V Dch V
125/147
125
KSOAP is a webservice client library for
constrained Java environments.SOAP protocol is widely used for machine-to-
machine interaction, it is strong-typed and supports
synchronous, asynchronous, and complex-routing
communication schemes.
Full download:
http://www.java2s.com/Code/Jar/k/ksoap2.htm
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice
http://www.java2s.com/Code/Jar/k/ksoap2.htmhttp://www.java2s.com/Code/Jar/k/ksoap2.htmhttp://www.java2s.com/Code/Jar/k/ksoap2.htmhttp://www.java2s.com/Code/Jar/k/ksoap2.htm -
8/11/2019 4 - X L a Tin Trnh V Dch V
126/147
126
Example 1: Get Primite Data from Computer Server
Use the getNumberOfCatalog() method in Webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 1: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
127/147
127
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 1: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
128/147
128
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
129/147
129
Example 2: Input Parameter, Add to PropertyInfo into SoapObject
request . Use the getMoney() method in Webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 2: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
130/147
130
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 2: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
131/147
131
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 2: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
132/147
132
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice
-
8/11/2019 4 - X L a Tin Trnh V Dch V
133/147
133
Example 3: get complex data. Use the getListCatalog() method in
Webservice
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 3: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
134/147
134
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 3: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
135/147
135
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 3: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
136/147
136
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice
E l 4 l d U h Li P d b C Id ()
http://192.168.3.102/ProductWebService/ProductWebService.asmx?op=getListProductbyCateIdhttp://192.168.3.102/ProductWebService/ProductWebService.asmx?op=getListProductbyCateId -
8/11/2019 4 - X L a Tin Trnh V Dch V
137/147
137
Example 4: get complex data. Use the getListProductbyCateId ()
method in Webservice
Take yourself (exercise)
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice
E l 5 I t S bObj t t b i
http://192.168.3.102/ProductWebService/ProductWebService.asmx?op=getListProductbyCateIdhttp://192.168.3.102/ProductWebService/ProductWebService.asmx?op=getListProductbyCateId -
8/11/2019 4 - X L a Tin Trnh V Dch V
138/147
138
Example 5: Insert SoabObject to webservice
Now in .Net, I add a new method with name insertCatalog,parameter is a catalog object
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 5: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
139/147
139
Also, add execNonquerymethod for Connectionfactory class
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 5: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
140/147
140
Please see the Soap description for insertCatalog method:
-
8/11/2019 4 - X L a Tin Trnh V Dch V
141/147
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 5: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
142/147
142
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 5: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
143/147
143
Coding to insert a new catalog
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 5: cont
-
8/11/2019 4 - X L a Tin Trnh V Dch V
144/147
144
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice
E l 6 h t t l A d id bil D i ith
-
8/11/2019 4 - X L a Tin Trnh V Dch V
145/147
145
Example 6: how to connect real Android mobile Device with
Computer Server (by Wireless)
Many ways:
1) Using Portable wifi hotspot (AndroidAp active)-
android mobile device has supports (you should
use this feature)
2) Connectivity software and other software (The
PC must use Win7, Win8)
3) Internet global
DONG NAI UNIVERSITY OF TECHNOLOGY
5.5 Android to .Net Webservice Example 6: cont
The figure I captured by Phone& Laptop Camera
-
8/11/2019 4 - X L a Tin Trnh V Dch V
146/147
146
Database + webservicein My Labtop
Here is my real Phone:SamSung S2
The figure I captured by Phone& Laptop Camera
Insert Cate
Get list Cate
Exercise: You must do that
DONG NAI UNIVERSITY OF TECHNOLOGY
-
8/11/2019 4 - X L a Tin Trnh V Dch V
147/147
END