SlideShare a Scribd company logo
1 of 25
Download to read offline
Programmation Mobile
Android
Rabie JABALLAH: jaballahrabie@gmail.com
Slim BENHAMMOUDA: slim.benhammouda@gmail.com
8. Content Providers and Databases
● Content providers manage access to a structured set of
data. They encapsulate the data, and provide
mechanisms for defining data security.
● Content providers are the standard interface that
connects data in one process with code running in
another process.
● Content providers allow exposing application data to
other applications
● Content providers handle inter-process communication
and secure data access.
Content Providers (2)
Content Providers
App 1 App 2
Share data
Search
Feature
Copy/Paste
complex data
File Data
Structured
Data
Handle
Add a level of
abstraction to Data
Handle Database
states
Widgets
CursorLoader and
Callback
SyncAdapter
Databases
● Android Supports SQLite database.
● To handle an SQLite database, we need an
“SQLiteDatabase” reference
○ SQLiteDatabase db = openOrCreateDatabase( "name", MODE_PRIVATE,
null); //openOrCreateDatabase called from a context
db.execSQL("SQL query");
Databases (2)
● methods:
– db.beginTransaction(), db.endTransaction()
– db.delete("table", "whereClause" , args)
– db.deleteDatabase(file)
– db.insert("table", null, values)
– db.query(...)
– db.rawQuery("SQL query", args)
– db.replace("table", null, values)
– db.update("table", values, "whereClause", args)
ContentValues
● ContentValues can be optionally used as a level of
abstraction for statements like INSERT, UPDATE,
REPLACE
● meant to allow using cleaner Java syntax rather than
raw SQL syntax for some common operations
ContentValues cvalues = new ContentValues(); cvalues.
put("columnName1", value1); cvalues.put("columnName2",
value2); ... db.insert("tableName", null, cvalues);
Cursor
● Cursor lets you iterate through row results one at a time
● Methods:
getBlob(index), getColumnCount(), getColumnIndex(name),
getColumnName(index), getCount(), getDouble(index),
getFloat(index), getInt(index), getLong(index),
getString(index), moveToPrevious(), ...
Cursor (2)
Cursor cursor = db.rawQuery("SELECT * FROM notes");
cursor.moveToFirst();
do {
int id = cursor.getInt(cursor.getColumnIndex("id"));
String email = cursor.getString( cursor.
getColumnIndex("email"));
...
} while (cursor.moveToNext());
cursor.close();
9. Broadcast Receivers
● A broadcast receiver (short receiver) is an Android
component which allows you to register for system or
application events. All registered receivers for an event
are notified by the Android runtime once this event
happens.
● it can be global (can be notified by other applications or
processes) or local (only notified by our appliocation)
● If it’s global, it must be declared in AndroidManifest.xml
● onReceive (Context context, Intent intent) has to be
implemented to handle received intent
10. Services
● service: A background task used by an app
- example: google play music plays the music using a service
- example: Web browser runs a downloader service to retrieve a file
- Useful for long-running tasks, and/or providing functionality that can
be used by other applications
● Android has two kinds of services:
- standard services: for longer jobs; remains running after app closes
- intent services: for shorter jobs; app launches them via intents
● When/if the service is done doing work, it can broadcast
this information to any receivers who are listening
10. Services (2)
Three ways to communicate with a service
- direct access: get the reference from the binder if the service is in
the same process as the activity that started it. In this case, we’re
talking about local services. public methods can be called directly.
Other applications can’t access this service
- Using a Handler and a Messenger: the service is running in another
process but in the same application. Handler and Messenger are
used to simplify IPC (interprocess communication) operations
- through aidl (Android Interface Definition Language): the service is
running in another process and can belong to another application. It’
s an interface for IPC.
The service lifecycle
● A service is started by an app’s activity using an intent
● Service operation modes:
- start: the service keeps running until it is manually stopped
- bind: the service keeps running until no “bound” apps are left
● Services have similar methods to activities for lifecycle
events
- onCreate, onDestroy
Adding a service in Android Studio
● right-click your project’s java package
● click New Service Service
Service class template
public class ServiceClassName extends Service {
/* this method handles a single incoming request */
@Override
public int onStartCommand(Intent intent, int flags, int id) {
// unpack any parameters that were passed to us
String value1 = intent.getStringExtra("key1");
String value2 = intent.getStringExtra("key2");
// do the work that the service needs to do ...
return START_STICKY; // stay running
}
@Override
public IBinder onBind(Intent intent) {
return null; // disable binding
}
}
AndroidManifets.xml changes
● to allow your app to use the service, add the following to
your app’s AndroidManifest.XML configuration:
(Android Studio does this for you if you use the New Service option)
- the exported attribut signifies whether other apps are also allowed
to use the service (true=yes, false=no)
<application…>
<service
android:name=”.ServiceClassName”
android:enable=”true”
android:exported=”false” />
Starting a service
● In your Activity class:
Intent intent = new Intent(this, ServiceClassName.class);
intent.putExtra("key1", "value1");
intent.putExtra("key2", "value2");
startService(intent); // not startActivity!
● or if the same code is launched from a
fragment
Intent intent = new Intent( getActivity(),
ServiceClassName.class);
...
Intent actions
● often a service has several “actions” or
commands it can perform
- example: a music player service can play, stop, pause,...
- example: a chat service can send, receive,...
Handler
● Handler: Represents a single piece of code to handle
one job in the queue
- Submit a job to the handler by calling its post method, passing a
Runnable object indicating the code to run
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
// the code to process the job
...
}
});
Handler (2)
● Handler support communication through a Messenger:
- to send messages, call sendMessage(Message msg)
- to handle received messages, we should implement the method
handleMessage (Message msg)
11. Multimedia
- The Android multimedia framework includes support for
playing variety of common media types,
- audio,
- video
- images
- You can play audio or video from media files stored in
your application's resources (raw resources), from
standalone files in the filesystem, or from a data stream
arriving over a network connection, all using
MediaPlayer APIs.
11. Multimedia (2)
http://developer.android.
com/guide/topics/media/media
player.html
12. Notifications
● notification: A message displayed to the user
outside of any app’s UI in a top notification
drawer area
- used to indicate system events, status of service tasks, etc
-
● notification can have:
- icons (small, large)
- a title
- a detailed description
- one or more associated actions that will occur when clicked
- ...
Notification properties
● setAutoCancel(boolean)
● setColor(argb)
● setContentIntent(intent)
● setContentText(“s”)
● setContentTitle(“s”)
● setGroup(“s”)
● setLargeIcon(bitmap)
● setLights(argb, onMs, offMs)
● setNumber(n)
● setSmallIcon(id)
● setSound(uri)
- whether to hide when clicked
- background color
- intent for action to run when clicked
- detailed description
- large heading text
- group similar notifications together
- image for big icon
- blinking lights
- a large number at right of notifications
- image file for icon
- a sound to play
Notification properties (2)
● setTicker(“s”)
● setVisibility(vis)
● setWhen(ms)
- text to scroll across top bar
- whether notification should show
- timestamp of notification
Notification with action
● Commonly, when the user clicks on a notification, an action should
occur. (redirect the user to a particular app / activity, etc
- To achieve this, use an intent inside your notification
- Must wrap it inside a “pending intent” object
Notification.Builder builder = ...;
Intent intent = new Intent(this, ActivityClassName.class);
intent.putExtra("key1", "value1");
...
PendingIntent pending = PendingIntent.getActivity(
this, 0, intent, 0);
builder.setContentIntent(pending);
Notification notification = builder.build();
...

More Related Content

What's hot

Android datastorage
Android datastorageAndroid datastorage
Android datastorageKrazy Koder
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data StorageMingHo Chang
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android DevelopmentJussi Pohjolainen
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageDroidConTLV
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture ComponentsBurhanuddinRashid
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsTonny Madsen
 
Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guideducquoc_vn
 
L0036 - Creating Views and Editors
L0036 - Creating Views and EditorsL0036 - Creating Views and Editors
L0036 - Creating Views and EditorsTonny Madsen
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitTonny Madsen
 
Sql grant, revoke, privileges and roles
Sql grant, revoke, privileges and rolesSql grant, revoke, privileges and roles
Sql grant, revoke, privileges and rolesVivek Singh
 
Yii in action
Yii in actionYii in action
Yii in actionKeaNy Chu
 
Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Cindy Potvin
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privilegesYogiji Creations
 

What's hot (20)

Android Data Storagefinal
Android Data StoragefinalAndroid Data Storagefinal
Android Data Storagefinal
 
Android Data Persistence
Android Data PersistenceAndroid Data Persistence
Android Data Persistence
 
Android datastorage
Android datastorageAndroid datastorage
Android datastorage
 
Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Android - Data Storage
Android - Data StorageAndroid - Data Storage
Android - Data Storage
 
Persistences
PersistencesPersistences
Persistences
 
Quick Intro to Android Development
Quick Intro to Android DevelopmentQuick Intro to Android Development
Quick Intro to Android Development
 
Android Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, VonageAndroid Architecture Components - Guy Bar on, Vonage
Android Architecture Components - Guy Bar on, Vonage
 
Android Architecture Components
Android Architecture ComponentsAndroid Architecture Components
Android Architecture Components
 
L0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard ViewsL0043 - Interfacing to Eclipse Standard Views
L0043 - Interfacing to Eclipse Standard Views
 
Ant_quick_guide
Ant_quick_guideAnt_quick_guide
Ant_quick_guide
 
L0036 - Creating Views and Editors
L0036 - Creating Views and EditorsL0036 - Creating Views and Editors
L0036 - Creating Views and Editors
 
L0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget ToolkitL0018 - SWT - The Standard Widget Toolkit
L0018 - SWT - The Standard Widget Toolkit
 
Sql grant, revoke, privileges and roles
Sql grant, revoke, privileges and rolesSql grant, revoke, privileges and roles
Sql grant, revoke, privileges and roles
 
Yii in action
Yii in actionYii in action
Yii in action
 
Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015Everything about storage - DroidconMtl 2015
Everything about storage - DroidconMtl 2015
 
User, roles and privileges
User, roles and privilegesUser, roles and privileges
User, roles and privileges
 
Lab4 - android
Lab4 - androidLab4 - android
Lab4 - android
 
Unit i informatica en ingles
Unit i informatica en inglesUnit i informatica en ingles
Unit i informatica en ingles
 

Viewers also liked

Développement Android
Développement AndroidDéveloppement Android
Développement AndroidFranck SIMON
 
Andcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexesAndcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexesCERTyou Formation
 
Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé Alphorm
 
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Loïc Knuchel
 
1cours virologie généralités (1)
1cours virologie généralités (1)1cours virologie généralités (1)
1cours virologie généralités (1)imlen gan
 
Devoxx 2015, ionic chat
Devoxx 2015, ionic chatDevoxx 2015, ionic chat
Devoxx 2015, ionic chatLoïc Knuchel
 
Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017Jasmine Conseil
 
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...Grégoire Arnould
 
Radio cognitive et intelligence artificielle
Radio cognitive et intelligence artificielleRadio cognitive et intelligence artificielle
Radio cognitive et intelligence artificiellebenouini rachid
 
Angular 4 - ngfor -- Français
Angular 4  - ngfor -- FrançaisAngular 4  - ngfor -- Français
Angular 4 - ngfor -- FrançaisVERTIKA
 
Algea - 04 - conclusion
Algea - 04 - conclusionAlgea - 04 - conclusion
Algea - 04 - conclusionYann Caron
 
Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015Loïc Knuchel
 
Angular 4 - regles -- Français
Angular 4  - regles -- FrançaisAngular 4  - regles -- Français
Angular 4 - regles -- FrançaisVERTIKA
 
Programmation Android - 00 - Présentation
Programmation Android - 00 - PrésentationProgrammation Android - 00 - Présentation
Programmation Android - 00 - PrésentationYann Caron
 
Mobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issuesMobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issuesOlivier Destrebecq
 

Viewers also liked (20)

Développement Android
Développement AndroidDéveloppement Android
Développement Android
 
Android à domicile
Android à domicileAndroid à domicile
Android à domicile
 
Andcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexesAndcx formation-android-avance-creation-d-applications-complexes
Andcx formation-android-avance-creation-d-applications-complexes
 
Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé Support de la formation Android 5 , Avancé
Support de la formation Android 5 , Avancé
 
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
 
1cours virologie généralités (1)
1cours virologie généralités (1)1cours virologie généralités (1)
1cours virologie généralités (1)
 
Devoxx 2015, ionic chat
Devoxx 2015, ionic chatDevoxx 2015, ionic chat
Devoxx 2015, ionic chat
 
Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017Meet up paris 13 of jun 2017
Meet up paris 13 of jun 2017
 
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
La Veille en E-Réputation et Community Management [2/3] : Outils, méthodologi...
 
Les virus
Les virusLes virus
Les virus
 
Mta
MtaMta
Mta
 
Montage video
Montage videoMontage video
Montage video
 
Radio cognitive et intelligence artificielle
Radio cognitive et intelligence artificielleRadio cognitive et intelligence artificielle
Radio cognitive et intelligence artificielle
 
Angular 4 - ngfor -- Français
Angular 4  - ngfor -- FrançaisAngular 4  - ngfor -- Français
Angular 4 - ngfor -- Français
 
Algea - 04 - conclusion
Algea - 04 - conclusionAlgea - 04 - conclusion
Algea - 04 - conclusion
 
Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015
 
Initiation aux echecs
Initiation aux echecsInitiation aux echecs
Initiation aux echecs
 
Angular 4 - regles -- Français
Angular 4  - regles -- FrançaisAngular 4  - regles -- Français
Angular 4 - regles -- Français
 
Programmation Android - 00 - Présentation
Programmation Android - 00 - PrésentationProgrammation Android - 00 - Présentation
Programmation Android - 00 - Présentation
 
Mobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issuesMobilization 2017: Don't lose your users because of endless quality issues
Mobilization 2017: Don't lose your users because of endless quality issues
 

Similar to 04 programmation mobile - android - (db, receivers, services...)

Android application development
Android application developmentAndroid application development
Android application developmentMd. Mujahid Islam
 
Hello android world
Hello android worldHello android world
Hello android worldeleksdev
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android DevelopmentAly Abdelkareem
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database faiz324545
 
Android task manager project presentation
Android task manager project presentationAndroid task manager project presentation
Android task manager project presentationAkhilesh Jaiswal
 
Synapseindia android application development tutorial
Synapseindia android application development tutorialSynapseindia android application development tutorial
Synapseindia android application development tutorialSynapseindiappsdevelopment
 
Synapseindia android apps development tutorial
Synapseindia android apps  development tutorialSynapseindia android apps  development tutorial
Synapseindia android apps development tutorialSynapseindiappsdevelopment
 
Nativa Android Applications development
Nativa Android Applications developmentNativa Android Applications development
Nativa Android Applications developmentAlfredo Morresi
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentalsAmr Salman
 
OS in mobile devices [Android]
OS in mobile devices [Android]OS in mobile devices [Android]
OS in mobile devices [Android]Yatharth Aggarwal
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & DatabasesMuhammad Sajid
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart JfokusLars Vogel
 

Similar to 04 programmation mobile - android - (db, receivers, services...) (20)

Android application development
Android application developmentAndroid application development
Android application development
 
Hello android world
Hello android worldHello android world
Hello android world
 
Android101
Android101Android101
Android101
 
Android beginners David
Android beginners DavidAndroid beginners David
Android beginners David
 
Introduction to Android Development
Introduction to Android DevelopmentIntroduction to Android Development
Introduction to Android Development
 
Ppt 2 android_basics
Ppt 2 android_basicsPpt 2 android_basics
Ppt 2 android_basics
 
Data Transfer between activities and Database
Data Transfer between activities and Database Data Transfer between activities and Database
Data Transfer between activities and Database
 
Unit2
Unit2Unit2
Unit2
 
Android Development Basics
Android Development BasicsAndroid Development Basics
Android Development Basics
 
Android
AndroidAndroid
Android
 
Android task manager project presentation
Android task manager project presentationAndroid task manager project presentation
Android task manager project presentation
 
Android Basic- CMC
Android Basic- CMCAndroid Basic- CMC
Android Basic- CMC
 
Best android classes in mumbai
Best android classes in mumbaiBest android classes in mumbai
Best android classes in mumbai
 
Synapseindia android application development tutorial
Synapseindia android application development tutorialSynapseindia android application development tutorial
Synapseindia android application development tutorial
 
Synapseindia android apps development tutorial
Synapseindia android apps  development tutorialSynapseindia android apps  development tutorial
Synapseindia android apps development tutorial
 
Nativa Android Applications development
Nativa Android Applications developmentNativa Android Applications development
Nativa Android Applications development
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentals
 
OS in mobile devices [Android]
OS in mobile devices [Android]OS in mobile devices [Android]
OS in mobile devices [Android]
 
Data Transfer between Activities & Databases
Data Transfer between Activities & DatabasesData Transfer between Activities & Databases
Data Transfer between Activities & Databases
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 

More from TECOS

Bouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecosBouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecosTECOS
 
D3 js-last
D3 js-lastD3 js-last
D3 js-lastTECOS
 
Summer internship
Summer internshipSummer internship
Summer internshipTECOS
 
Mohamed bouhamed - ccna2
Mohamed bouhamed  - ccna2Mohamed bouhamed  - ccna2
Mohamed bouhamed - ccna2TECOS
 
Mohamed bouhamed - ccna1
Mohamed bouhamed  -  ccna1Mohamed bouhamed  -  ccna1
Mohamed bouhamed - ccna1TECOS
 
Mobile certified
Mobile certifiedMobile certified
Mobile certifiedTECOS
 
Analytics certified
Analytics certifiedAnalytics certified
Analytics certifiedTECOS
 
Ad words certified
Ad words certifiedAd words certified
Ad words certifiedTECOS
 
Télémétrie d’openstack
Télémétrie d’openstackTélémétrie d’openstack
Télémétrie d’openstackTECOS
 
cloudu certification
cloudu certificationcloudu certification
cloudu certificationTECOS
 
Internship report
Internship reportInternship report
Internship reportTECOS
 
Gsm presntation
Gsm presntationGsm presntation
Gsm presntationTECOS
 
Td gsm iit
Td gsm iitTd gsm iit
Td gsm iitTECOS
 
Complément réseaux informatiques
Complément réseaux informatiquesComplément réseaux informatiques
Complément réseaux informatiquesTECOS
 
Cours réseauxs gsm
Cours réseauxs gsmCours réseauxs gsm
Cours réseauxs gsmTECOS
 
Cours sécurité 2_asr
Cours sécurité 2_asrCours sécurité 2_asr
Cours sécurité 2_asrTECOS
 
chapitre 1
chapitre 1chapitre 1
chapitre 1TECOS
 
Serveur web iit_asr_p2i
Serveur web iit_asr_p2iServeur web iit_asr_p2i
Serveur web iit_asr_p2iTECOS
 
Examen
Examen Examen
Examen TECOS
 
01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)TECOS
 

More from TECOS (20)

Bouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecosBouhamed vuejs-meetup-tecos
Bouhamed vuejs-meetup-tecos
 
D3 js-last
D3 js-lastD3 js-last
D3 js-last
 
Summer internship
Summer internshipSummer internship
Summer internship
 
Mohamed bouhamed - ccna2
Mohamed bouhamed  - ccna2Mohamed bouhamed  - ccna2
Mohamed bouhamed - ccna2
 
Mohamed bouhamed - ccna1
Mohamed bouhamed  -  ccna1Mohamed bouhamed  -  ccna1
Mohamed bouhamed - ccna1
 
Mobile certified
Mobile certifiedMobile certified
Mobile certified
 
Analytics certified
Analytics certifiedAnalytics certified
Analytics certified
 
Ad words certified
Ad words certifiedAd words certified
Ad words certified
 
Télémétrie d’openstack
Télémétrie d’openstackTélémétrie d’openstack
Télémétrie d’openstack
 
cloudu certification
cloudu certificationcloudu certification
cloudu certification
 
Internship report
Internship reportInternship report
Internship report
 
Gsm presntation
Gsm presntationGsm presntation
Gsm presntation
 
Td gsm iit
Td gsm iitTd gsm iit
Td gsm iit
 
Complément réseaux informatiques
Complément réseaux informatiquesComplément réseaux informatiques
Complément réseaux informatiques
 
Cours réseauxs gsm
Cours réseauxs gsmCours réseauxs gsm
Cours réseauxs gsm
 
Cours sécurité 2_asr
Cours sécurité 2_asrCours sécurité 2_asr
Cours sécurité 2_asr
 
chapitre 1
chapitre 1chapitre 1
chapitre 1
 
Serveur web iit_asr_p2i
Serveur web iit_asr_p2iServeur web iit_asr_p2i
Serveur web iit_asr_p2i
 
Examen
Examen Examen
Examen
 
01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)01 programmation mobile - android - (introduction)
01 programmation mobile - android - (introduction)
 

04 programmation mobile - android - (db, receivers, services...)

  • 1. Programmation Mobile Android Rabie JABALLAH: jaballahrabie@gmail.com Slim BENHAMMOUDA: slim.benhammouda@gmail.com
  • 2. 8. Content Providers and Databases ● Content providers manage access to a structured set of data. They encapsulate the data, and provide mechanisms for defining data security. ● Content providers are the standard interface that connects data in one process with code running in another process. ● Content providers allow exposing application data to other applications ● Content providers handle inter-process communication and secure data access.
  • 3. Content Providers (2) Content Providers App 1 App 2 Share data Search Feature Copy/Paste complex data File Data Structured Data Handle Add a level of abstraction to Data Handle Database states Widgets CursorLoader and Callback SyncAdapter
  • 4. Databases ● Android Supports SQLite database. ● To handle an SQLite database, we need an “SQLiteDatabase” reference ○ SQLiteDatabase db = openOrCreateDatabase( "name", MODE_PRIVATE, null); //openOrCreateDatabase called from a context db.execSQL("SQL query");
  • 5. Databases (2) ● methods: – db.beginTransaction(), db.endTransaction() – db.delete("table", "whereClause" , args) – db.deleteDatabase(file) – db.insert("table", null, values) – db.query(...) – db.rawQuery("SQL query", args) – db.replace("table", null, values) – db.update("table", values, "whereClause", args)
  • 6. ContentValues ● ContentValues can be optionally used as a level of abstraction for statements like INSERT, UPDATE, REPLACE ● meant to allow using cleaner Java syntax rather than raw SQL syntax for some common operations ContentValues cvalues = new ContentValues(); cvalues. put("columnName1", value1); cvalues.put("columnName2", value2); ... db.insert("tableName", null, cvalues);
  • 7. Cursor ● Cursor lets you iterate through row results one at a time ● Methods: getBlob(index), getColumnCount(), getColumnIndex(name), getColumnName(index), getCount(), getDouble(index), getFloat(index), getInt(index), getLong(index), getString(index), moveToPrevious(), ...
  • 8. Cursor (2) Cursor cursor = db.rawQuery("SELECT * FROM notes"); cursor.moveToFirst(); do { int id = cursor.getInt(cursor.getColumnIndex("id")); String email = cursor.getString( cursor. getColumnIndex("email")); ... } while (cursor.moveToNext()); cursor.close();
  • 9. 9. Broadcast Receivers ● A broadcast receiver (short receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event are notified by the Android runtime once this event happens. ● it can be global (can be notified by other applications or processes) or local (only notified by our appliocation) ● If it’s global, it must be declared in AndroidManifest.xml ● onReceive (Context context, Intent intent) has to be implemented to handle received intent
  • 10. 10. Services ● service: A background task used by an app - example: google play music plays the music using a service - example: Web browser runs a downloader service to retrieve a file - Useful for long-running tasks, and/or providing functionality that can be used by other applications ● Android has two kinds of services: - standard services: for longer jobs; remains running after app closes - intent services: for shorter jobs; app launches them via intents ● When/if the service is done doing work, it can broadcast this information to any receivers who are listening
  • 11. 10. Services (2) Three ways to communicate with a service - direct access: get the reference from the binder if the service is in the same process as the activity that started it. In this case, we’re talking about local services. public methods can be called directly. Other applications can’t access this service - Using a Handler and a Messenger: the service is running in another process but in the same application. Handler and Messenger are used to simplify IPC (interprocess communication) operations - through aidl (Android Interface Definition Language): the service is running in another process and can belong to another application. It’ s an interface for IPC.
  • 12. The service lifecycle ● A service is started by an app’s activity using an intent ● Service operation modes: - start: the service keeps running until it is manually stopped - bind: the service keeps running until no “bound” apps are left ● Services have similar methods to activities for lifecycle events - onCreate, onDestroy
  • 13. Adding a service in Android Studio ● right-click your project’s java package ● click New Service Service
  • 14. Service class template public class ServiceClassName extends Service { /* this method handles a single incoming request */ @Override public int onStartCommand(Intent intent, int flags, int id) { // unpack any parameters that were passed to us String value1 = intent.getStringExtra("key1"); String value2 = intent.getStringExtra("key2"); // do the work that the service needs to do ... return START_STICKY; // stay running } @Override public IBinder onBind(Intent intent) { return null; // disable binding } }
  • 15. AndroidManifets.xml changes ● to allow your app to use the service, add the following to your app’s AndroidManifest.XML configuration: (Android Studio does this for you if you use the New Service option) - the exported attribut signifies whether other apps are also allowed to use the service (true=yes, false=no) <application…> <service android:name=”.ServiceClassName” android:enable=”true” android:exported=”false” />
  • 16. Starting a service ● In your Activity class: Intent intent = new Intent(this, ServiceClassName.class); intent.putExtra("key1", "value1"); intent.putExtra("key2", "value2"); startService(intent); // not startActivity! ● or if the same code is launched from a fragment Intent intent = new Intent( getActivity(), ServiceClassName.class); ...
  • 17. Intent actions ● often a service has several “actions” or commands it can perform - example: a music player service can play, stop, pause,... - example: a chat service can send, receive,...
  • 18. Handler ● Handler: Represents a single piece of code to handle one job in the queue - Submit a job to the handler by calling its post method, passing a Runnable object indicating the code to run Handler handler = new Handler(); handler.post(new Runnable() { public void run() { // the code to process the job ... } });
  • 19. Handler (2) ● Handler support communication through a Messenger: - to send messages, call sendMessage(Message msg) - to handle received messages, we should implement the method handleMessage (Message msg)
  • 20. 11. Multimedia - The Android multimedia framework includes support for playing variety of common media types, - audio, - video - images - You can play audio or video from media files stored in your application's resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection, all using MediaPlayer APIs.
  • 22. 12. Notifications ● notification: A message displayed to the user outside of any app’s UI in a top notification drawer area - used to indicate system events, status of service tasks, etc - ● notification can have: - icons (small, large) - a title - a detailed description - one or more associated actions that will occur when clicked - ...
  • 23. Notification properties ● setAutoCancel(boolean) ● setColor(argb) ● setContentIntent(intent) ● setContentText(“s”) ● setContentTitle(“s”) ● setGroup(“s”) ● setLargeIcon(bitmap) ● setLights(argb, onMs, offMs) ● setNumber(n) ● setSmallIcon(id) ● setSound(uri) - whether to hide when clicked - background color - intent for action to run when clicked - detailed description - large heading text - group similar notifications together - image for big icon - blinking lights - a large number at right of notifications - image file for icon - a sound to play
  • 24. Notification properties (2) ● setTicker(“s”) ● setVisibility(vis) ● setWhen(ms) - text to scroll across top bar - whether notification should show - timestamp of notification
  • 25. Notification with action ● Commonly, when the user clicks on a notification, an action should occur. (redirect the user to a particular app / activity, etc - To achieve this, use an intent inside your notification - Must wrap it inside a “pending intent” object Notification.Builder builder = ...; Intent intent = new Intent(this, ActivityClassName.class); intent.putExtra("key1", "value1"); ... PendingIntent pending = PendingIntent.getActivity( this, 0, intent, 0); builder.setContentIntent(pending); Notification notification = builder.build(); ...