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

Post on 27-Jul-2015

195 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Programmation Mobile Android

Rabie JABALLAH: jaballahrabie@gmail.comSlim 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 templatepublic 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/mediaplayer.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();

...

top related