85
Chapter 5 Intent: Android uses Intent for communicating between the components of an Application and also from one application to another application. Intent are the objects which is used in android for passing the information among Activities in an Application and from one app to another also. Intent are used for communicating between the Application components and it also provides the connectivity between two apps. Example- Intent intent = new Intent(getApplicationContext(), SecondActivity.class); startActivity(intent); getApplicationContext() returns the context for your foreground activity. Types of intent: Explicit Intent: Explicit Intents are used to connect the application internally. Explicit Intent work internally within an application to perform navigation and data transfer. Example- Intent intent = new Intent(getApplicationContext(), SecondActivity.class); startActivity(intent);

Chapter 5 Intent

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Chapter 5 Intent

Chapter 5

Intent:

Android uses Intent for communicating between the components of an Application and also from

one application to another application.

Intent are the objects which is used in android for passing the information among

Activities in an Application and from one app to another also. Intent are used for communicating

between the Application components and it also provides the connectivity between two apps.

Example-

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);

startActivity(intent);

getApplicationContext() returns the context for your foreground activity.

Types of intent:

Explicit Intent:

Explicit Intents are used to connect the application internally.

Explicit Intent work internally within an application to perform navigation and data

transfer.

Example-

Intent intent = new Intent(getApplicationContext(), SecondActivity.class);

startActivity(intent);

Page 2: Chapter 5 Intent

Implicit Intent:

In Implicit Intents we do need to specify the name of the component. We just specify the

Action which has to be performed and further this action is handled by the component of another

application.

The basic example of implicit Intent is to open any web page

Example-

Intent intentObj = new Intent(Intent.ACTION_VIEW);

intentObj.setData(Uri.parse("https://www.abhiandroid.com"));

startActivity(intentObj);

Intent Uses in android:

Intent for an Activity:

Every screen in Android application represents an activity. To start a new activity you

need to pass an Intent object to startActivity() method. This Intent object helps to start a new

activity and passing data to the second activity.

Intent for Services:

Services work in background of an Android application and it does not require any user

Interface. Intents could be used to start a Service that performs one-time task(for example:

Downloading some file)

Intent for Broadcast Receivers:

There are various message that an app receives, these messages are called as Broadcast

Receivers. (For example, a broadcast message could be initiated to intimate that the file

downloading is completed and ready to use). Android system initiates some broadcast message

on several events, such as System Reboot, Low Battery warning message etc.

Intent Filter:

-decide the behavior of an intent.

-Intent about the navigation of one activity to another,that can be achieve by

declaring intent filter.

-We can declare an Intent Filter for an Activity in manifest file.

- Intent filters specify the type of intents that an Activity, service or Broadcast receiver can

respond to.

Page 3: Chapter 5 Intent

• Syntax of Intent Filters:

<activity android:name=".MainActivity">

<intent-filter

android:icon="@drawable/icon" android:label="@string/label" >

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" /> </intent-filter>

</activity>

• icon: This is displayed as icon for activity. You can check or save png image of name

icon in drawable folder.

android:icon="@drawable/icon"

• label: The label / title that appears at top in Toolbar of that particular Activity. You can

check or edit label name by opening String XML file present inside Values folder

android:label = "@string/label“

or

android:label = "New Activity“

Just like icon attribute, if you have not declared any label for your activity then it

will be same as your parent activity.

• Elements In Intent Filter:

There are following three elements in an intent filter:

1.Action

2.Data

3.Category

Activity Lifecycle:

Activity is a screen that user interact with. Every Activity in android has lifecycle

like created, started, resumed, paused, stopped or destroyed. These different states are

known as Activity Lifecycle.

onCreate() – Called when the activity is first created

onStart() – Called just after it’s creation or by restart method after onStop(). Here

Activity start becoming visible to user

Page 4: Chapter 5 Intent

onResume() –

Called when Activity is visible to user and user can interact with it

onPause() – Called when Activity content is not visible because user resume previous

activity

onStop() – Called when activity is not visible to user because some other activity takes

place of it

onRestart() – Called when user comes on screen or resume the activity which was

stopped

onDestroy – Called when Activity is not in background

Diagram:

Page 5: Chapter 5 Intent

Broadcast Receiver

Broadcast Receiver is a component which will allow android system or other apps to

deliver events to the app like sending a low battery message or screen turned off message to the

app. The apps can also initiate broadcasts to let other apps know that required data available in a

device to use it.

Generally, we use Intents to deliver broadcast events to other apps and Broadcast

Receivers use status bar notifications to let user know that broadcast event occurs.

is implemented as a subclass of BroadcastReceiver and each broadcast is delivered as

an Intent object.

two important steps to make BroadcastReceiver:

• Registering Broadcast Receiver

• Creating the Broadcast Receiver

A broadcast receiver is implemented as a subclass of BroadcastReceiver class and

overriding the onReceive() method where each message is received as a Intent object parameter.

Example-

public class MyReceiver extends BroadcastReceiver

{

public void onReceive(Context context, Intent intent)

{

Toast.makeText(context, "Intent Detected.",

Toast.LENGTH_LONG).show(); } }

System generated events are:

• android.intent.action.BATTERY_CHANGED

• android.intent.action.BATTERY_LOW

• android.intent.action.BATTERY_OKAY

• android.intent.action.BOOT_COMPLETED

• android.intent.action.BUG_REPORT

• android.intent.action.CALL

• android.intent.action.CALL_BUTTON

• android.intent.action.DATE_CHANGED

Page 6: Chapter 5 Intent

• android.intent.action.REBOOT

Content Provider:

Content Provider will act as a central repository to store the applications data in one

place and make that data available for different applications to access whenever it’s required.

the Content Provider is a part of an android application and it will act as more like

relational database to store the app data. We can perform a multiple operations like insert,

update, delete and edit on the data stored in content provider

using insert(), update(), delete() and query() methods.

content provider is having different ways to store app data. The app data can be stored in

a SQLite database or in files or even over a network based on our requirements. By using content

providers we can manage data such as audio, video, images and personal contact information.

Page 7: Chapter 5 Intent

• ContentResolver-

To access a data from content provider,

we need to use ContentResolver

• CursorLoader-

is used to run the query asynchronously in

background

• ContentProvider-

receive a data requests from client,

performs the requested actions

(create, update, delete, retrieve)

and return the result.

• Content URIs:

To query a content provider, you specify the query string in the form of a URI which has

following format −

content://authority/path

content:// - The string content:// is always present in the URI

authority - It represents the name of content provider

path - It represents the table’s path.

The ContentResolver object use the URI’s authority to find the appropriate provider and

send the query objects to the correct provider. After that ContentProvider uses the path of

content URI to choose the right table to access.

Page 8: Chapter 5 Intent

To create a content provider in android applications we should follow below

steps.

1. We need to create a content provider class that extends the ContentProvider base class.

2. We need to define our content provider URI to access the content.

3. The ContentProvider class defines a six abstract methods (insert(), update(), delete(),

query(), getType()) which we need to implement all these methods as a part of our

subclass.

4. We need to register our content provider in AndroidManifest.xml using <provider> tag.

Methods:

1. query() - It receives a request from the client. By using arguments it will get a data

from requested table and return the data as a Cursor object.

2. insert() - This method will insert a new row into our content provider and it will

return the content URI for newly inserted row.

3. update() - This method will update an existing rows in our content provider and it

return the number of rows updated.

4. delete() - This method will delete the rows in our content provider and it return the

number of rows deleted.

5. getType() - This method will return the MIME type of data to given content URI.

6. onCreate() - This method will initialize our provider. The android system will call

this method immediately after it creates our provider.

Fragment:

Fragment is a part of an activity which enable more modular activity design. It will not be wrong

if we say a fragment is a kind of sub-activity.

We can combine multiple Fragments in Single Activity to build a multi panel UI and

reuse a Fragment in multiple Activities.

• A fragment has its own layout and its own behaviour with its own life cycle callbacks.

• You can add or remove fragments in an activity while the activity is running.

• You can combine multiple fragments in a single activity to build a multi-pane UI.

• A fragment can be used in multiple activities.

Page 9: Chapter 5 Intent

• Fragment life cycle is closely related to the life cycle of its host activity which means

when the activity is paused, all the fragments available in the activity will also be

stopped.

Need of Fragment:

• Before the introduction of Fragment’s we can only show a single Activity on the screen

at one given point of time so we were not able to divide the screen and control different

parts separately. With the help of Fragment’s we can divide the screens in different parts

and controls different parts separately.

• By using Fragments we can comprise multiple Fragments in a single Activity. Fragments

have their own events, layouts and complete life cycle. It provide flexibility and also

removed the limitation of single Activity on the screen at a time.

Fragment code example in XML:

<fragment

android:id="@+id/fragments"

android:layout_width="match_parent"

android:layout_height="match_parent" />

Fragment Life cycle:

Page 10: Chapter 5 Intent

Description:

• onAttach() is called when a fragment is connected to an activity.

• onCreate() is called to do initial creation of the fragment.

• onCreateView() is called by Android once the Fragment should inflate a view.

• onViewCreated() is called after onCreateView() and ensures that the fragment's root view

is non-null. Any view setup should happen here. E.g., view lookups, attaching listeners.

• onActivityCreated() is called when host activity has completed its onCreate() method.

• onStart() is called once the fragment is ready to be displayed on screen.

• onResume() - Allocate “expensive” resources such as registering for location, sensor

updates, etc.

• onPause() - Release “expensive” resources. Commit any changes.

• onDestroyView() is called when fragment's view is being destroyed, but the fragment is

still kept around.

• onDestroy() is called when fragment is no longer in use.

• onDetach() is called when fragment is no longer connected to the activity.

Types of Fragment :

• Single frame fragments − Single frame fragments are using for hand hold devices like

mobiles, here we can show only one fragment as a view.

• List fragments − fragments having special list view is called as list fragment

• Fragments transaction − Using with fragment transaction. we can move one fragment to

another fragment

Services:

Android service is a component that is used to perform operations on the

background such as playing music, handle network transactions, interacting content

providers etc. It doesn't has any UI (user interface).

The service runs in the background indefinitely even if application is destroyed.

• three different types of services:

1. Foreground- A foreground service performs some operation that is noticeable to

the user.

2. Background- A background service performs an operation that isn't directly

noticed by the user.

Page 11: Chapter 5 Intent

3. Bound- A service is bound when an application component binds to it by

calling bindService(). A bound service offers a client-server interface that allows components

to interact with the service, send requests, receive results, and even do so across processes

with interprocess communication (IPC). A bound service runs only as long as another

application component is bound to it. Multiple components can bind to the service at once,

but when all of them unbind, the service is destroyed.

A service can essentially take two states −

• Started

A service is started when an application component, such as an activity, starts it by

calling startService(). Once started, a service can run in the background indefinitely, even if

the component that started it is destroyed.

• Bound

A service is bound when an application component binds to it by calling bindService().

A bound service offers a client-server interface that allows components to interact with the

service, send requests, get results, and even do so across processes with interprocess

communication (IPC).

Life cycle of service:

Page 12: Chapter 5 Intent

• onStartCommand()

The system calls this method when another component, such as an activity, requests that

the service be started, by calling startService(). If you implement this method, it is your

responsibility to stop the service when its work is done, by

calling stopSelf() or stopService() methods.

• onBind()

The system calls this method when another component wants to bind with the service by

calling bindService(). If you implement this method, you must provide an interface that

clients use to communicate with the service, by returning an IBinder object. You must

always implement this method, but if you don't want to allow binding, then you should

return null.

• onUnbind()

The system calls this method when all clients have disconnected from a particular

interface published by the service.

• onRebind()

The system calls this method when new clients have connected to the service, after it had

previously been notified that all had disconnected in its onUnbind(Intent).

• onCreate()

The system calls this method when the service is first created

using onStartCommand() or onBind(). This call is required to perform one-time set-up.

• onDestroy()

The system calls this method when the service is no longer used and is being destroyed.

Your service should implement this to clean up any resources such as threads, registered

listeners, receivers, etc.

• Create a Service

Generally, in android to create a service we must create a subclass of Service . In android

the application component such as an activity can start the service by

calling startService() which results in calling the service’s onStartCommand() method.

Page 13: Chapter 5 Intent

public class SampleService extends Service

{

@Override

public int onStartCommand(Intent intent, int flags, int startId)

{

//TODO write your own code

return Service.START_NOT_STICKY;

}

@Override

public IBinder onBind(Intent intent)

{

//TODO for communication return IBinder implementation

return null;

}

}

• Register a Service in Manifest File

<manifest ... >

...

<application ... >

<service android:name=".SampleService" />

</application>

...

</manifest>

• Start a Service

Intent intent = new Intent(this, MyService.class);

startService(intent);

The onStartCommand() method will return a value from one of the following

constants.

1. START_STICKY

It will restart the service in case if it terminated and the Intent data which is passed

to onStartCommand() method is NULL. This is suitable for the service which are not executing

commands but running independently and waiting for the job.

Page 14: Chapter 5 Intent

2. START_NOT_STICKY

It will not restart the service and it is useful for the services which will run periodically. The

service will restart only when there are a pending startService() calls. It’s a best option to

avoid running a service in case if it is not necessary.

3. START_REDELIVER_INTENT

It’s same as STAR_STICY and it recreates the service, call onStartCommand() with

last intent that was delivered to the service.

Android Architecture:

Android operating system is a stack of software components which is roughly divided into

five sections and four main layers as shown below in the architecture diagram.

Linux kernel

At the bottom of the layers is Linux - Linux 3.6 with approximately 115 patches. This provides a

level of abstraction between the device hardware and it contains all the essential hardware drivers

like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good

Page 15: Chapter 5 Intent

at such as networking and a vast array of device drivers, which take the pain out of interfacing to

peripheral hardware.

Libraries

On top of Linux kernel there is a set of libraries including open-source Web browser engine

WebKit, well known library libc, SQLite database which is a useful repository for storage and

sharing of application data, libraries to play and record audio and video, SSL libraries responsible

for Internet security etc.

Android Libraries

This category encompasses those Java-based libraries that are specific to Android development.

Examples of libraries in this category include the application framework libraries in addition to

those that facilitate user interface building, graphics drawing and database access. A summary of

some key core Android libraries available to the Android developer is as follows −

• android.app − Provides access to the application model and is the cornerstone of all

Android applications.

• android.content − Facilitates content access, publishing and messaging between

applications and application components.

• android.database − Used to access data published by content providers and includes

SQLite database management classes.

• android.opengl − A Java interface to the OpenGL ES 3D graphics rendering API.

• android.os − Provides applications with access to standard operating system services

including messages, system services and inter-process communication.

• android.text − Used to render and manipulate text on a device display.

• android.view − The fundamental building blocks of application user interfaces.

• android.widget − A rich collection of pre-built user interface components such as buttons,

labels, list views, layout managers, radio buttons etc.

• android.webkit − A set of classes intended to allow web-browsing capabilities to be built

into applications.

Having covered the Java-based core libraries in the Android runtime, it is now time to turn our

attention to the C/C++ based libraries contained in this layer of the Android software stack.

Android Runtime

This is the third section of the architecture and available on the second layer from the bottom.

This section provides a key component called Dalvik Virtual Machine which is a kind of Java

Virtual Machine specially designed and optimized for Android.

Page 16: Chapter 5 Intent

The Dalvik VM makes use of Linux core features like memory management and multi-threading,

which is intrinsic in the Java language. The Dalvik VM enables every Android application to run

in its own process, with its own instance of the Dalvik virtual machine.

The Android runtime also provides a set of core libraries which enable Android application

developers to write Android applications using standard Java programming language.

Application Framework

The Application Framework layer provides many higher-level services to applications in the form

of Java classes. Application developers are allowed to make use of these services in their

applications.

The Android framework includes the following key services −

• Activity Manager − Controls all aspects of the application lifecycle and activity stack.

• Content Providers − Allows applications to publish and share data with other

applications.

• Resource Manager − Provides access to non-code embedded resources such as strings,

color settings and user interface layouts.

• Notifications Manager − Allows applications to display alerts and notifications to the

user.

• View System − An extensible set of views used to create application user interfaces.

Applications

You will find all the Android application at the top layer. You will write your application to be

installed on this layer only. Examples of such applications are Contacts Books, Browser, Games

etc.

Multimedia Framework:

A multimedia framework is a software framework that handles media on a computer and through

a network. A good multimedia framework offers an intuitive API and a modular architecture to

easily add support for new audio, video and container formats and transmission protocols. It is

meant to be used by applications such as media players and audio or video editors, but can also

be used to build videoconferencing applications, media converters and other multimedia tools.

Data is processed among modules automatically, it is unnecessary for app to pass buffers

between connected modules one by one.

In contrast to function libraries, a multimedia framework provides a run time environment for the

media processing. Ideally such an environment provides execution contexts for the media

processing blocks separated from the application using the framework. The separation supports

the independent processing of multimedia data in a timely manner. These separate contexts can

be implemented as threads

Page 17: Chapter 5 Intent

Bluetooth:

Bluetooth is a way to send or receive data between two different devices. Android platform

includes support for the Bluetooth framework that allows a device to wirelessly exchange data

with other Bluetooth devices.

Android provides Bluetooth API to perform these different operations.

• Scan for other Bluetooth devices

• Get a list of paired devices

• Connect to other devices through service discovery

Android provides BluetoothAdapter class to communicate with Bluetooth. Create an object of

this calling by calling the static method getDefaultAdapter(). Its syntax is given below.

private BluetoothAdapter BA;

BA = BluetoothAdapter.getDefaultAdapter();

In order to enable the Bluetooth of your device, call the intent with the following Bluetooth

constant ACTION_REQUEST_ENABLE. Its syntax is.

Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

startActivityForResult(turnOn, 0);

Apart from this constant, there are other constants provided the API , that supports different tasks.

They are listed below.

Sr.No Constant & description

1 ACTION_REQUEST_DISCOVERABLE

This constant is used for turn on discovering of bluetooth

2 ACTION_STATE_CHANGED

This constant will notify that Bluetooth state has been changed

3 ACTION_FOUND

This constant is used for receiving information about each device that is discovered

Once you enable the Bluetooth , you can get a list of paired devices by calling

getBondedDevices() method. It returns a set of bluetooth devices. Its syntax is.

private Set<BluetoothDevice>pairedDevices;

Page 18: Chapter 5 Intent

pairedDevices = BA.getBondedDevices();

Apart form the parried Devices , there are other methods in the API that gives more control over

Blueetooth. They are listed below.

Sr.No Method & description

1 enable()

This method enables the adapter if not enabled

2 isEnabled()

This method returns true if adapter is enabled

3 disable()

This method disables the adapter

4 getName()

This method returns the name of the Bluetooth adapter

5 setName(String name)

This method changes the Bluetooth name

6 getState()

This method returns the current state of the Bluetooth Adapter.

7 startDiscovery()

This method starts the discovery process of the Bluetooth for 120 seconds.

Example

This example provides demonstration of BluetoothAdapter class to manipulate Bluetooth and

show list of paired devices by the Bluetooth.

To experiment with this example , you need to run this on an actual device.

Page 19: Chapter 5 Intent

Steps Description

1 You will use Android studio to create an Android application a package

com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add the code

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

4 Modify AndroidManifest.xml to add necessary permissions.

5 Run the application and choose a running android device and install the application on it and verify

the results.

Animation:

Animation in android is possible from many ways. In this chapter we will discuss one easy and

widely used way of making animation called tweened animation.

Tween Animation

Tween Animation takes some parameters such as start value , end value, size , time duration ,

rotation angle e.t.c and perform the required animation on that object. It can be applied to any

type of object. So in order to use this , android has provided us a class called Animation.

In order to perform animation in android , we are going to call a static function loadAnimation()

of the class AnimationUtils. We are going to receive the result in an instance of Animation Object.

Its syntax is as follows −

Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),

R.anim.myanimation);

Note the second parameter. It is the name of the our animation xml file. You have to create a new

folder called anim under res directory and make an xml file under anim folder.

This animation class has many useful functions which are listed below −

Sr.No Method & Description

Page 20: Chapter 5 Intent

1 start()

This method starts the animation.

2 setDuration(long duration)

This method sets the duration of an animation.

3 getDuration()

This method gets the duration which is set by above method

4 end()

This method ends the animation.

5 cancel()

This method cancels the animation.

In order to apply this animation to an object , we will just call the startAnimation() method of the

object. Its syntax is −

ImageView image1 = (ImageView)findViewById(R.id.imageView1);

image.startAnimation(animation);

Example

The following example demonstrates the use of Animation in android. You would be able to

choose different type of animation from the menu and the selected animation will be applied on

an imageView on the screen.

To experiment with this example , you need to run this on an emulator or an actual device.

Steps Description

1 You will use Android studio IDE to create an Android application and name it as My Application under a package

com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add animation code

Page 21: Chapter 5 Intent

3 Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

4 Create a new folder under res directory and call it anim. Confim it by visiting res/anim

5 Right click on anim and click on new and select Android XML file You have to create different files that are listed

below.

6 Create files myanimation.xml,clockwise.xml,fade.xml,move.xml,blink.xml,slide.xml and add the XML code.

7 No need to change default string constants. Android studio takes care of default constants at values/string.xml.

8 Run the application and choose a running android device and install the application on it and verify the results.

Camera:

These are the following two ways, in which you can use camera in your application

• Using existing android camera application in our application

• Directly using Camera API provided by android in our application

Using existing android camera application in our application

You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an existing camera

application installed on your phone. Its syntax is given below

Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

Apart from the above, there are other available Intents provided by MediaStore. They are listed

as follows

Sr.No Intent type and description

1 ACTION_IMAGE_CAPTURE_SECURE

It returns the image captured from the camera , when the device is secured

2 ACTION_VIDEO_CAPTURE

Page 22: Chapter 5 Intent

It calls the existing video application in android to capture video

3 EXTRA_SCREEN_ORIENTATION

It is used to set the orientation of the screen to vertical or landscape

4 EXTRA_FULL_SCREEN

It is used to control the user interface of the ViewImage

5 INTENT_ACTION_VIDEO_CAMERA

This intent is used to launch the camera in the video mode

6 EXTRA_SIZE_LIMIT

It is used to specify the size limit of video or image capture size

Now you will use the function startActivityForResult() to launch this activity and wait for its

result. Its syntax is given below

startActivityForResult(intent,0)

This method has been defined in the activity class. We are calling it from main activity. There

are methods defined in the activity class that does the same job , but used when you are not calling

from the activity but from somewhere else. They are listed below

Sr.No Activity function description

1 startActivityForResult(Intent intent, int requestCode, Bundle options)

It starts an activity , but can take extra bundle of options with it

2 startActivityFromChild(Activity child, Intent intent, int requestCode)

It launch the activity when your activity is child of any other activity

3 startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options)

It work same as above , but it can take extra values in the shape of bundle with it

Page 23: Chapter 5 Intent

4 startActivityFromFragment(Fragment fragment, Intent intent, int requestCode)

It launches activity from the fragment you are currently inside

5

startActivityFromFragment(Fragment fragment, Intent intent, int requestCode, Bundle

options)

It not only launches the activity from the fragment , but can take extra values with it

No matter which function you used to launch the activity , they all return the result. The result

can be obtained by overriding the function onActivityResult.

Example

Here is an example that shows how to launch the existing camera application to capture an image

and display the result in the form of bitmap.

To experiment with this example , you need to run this on an actual device on which camera is

supported.

Steps Description

1 You will use Android studio IDE to create an Android application and name it as Camera under a

com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to add intent code to launch the Camera.

3 Modify layout XML file res/layout/activity_main.xml

4 Add the Camera permission and run the application and choose a running android device and install

the application on it and verify the results.

Page 24: Chapter 5 Intent

Audio and Video player:

• Android provides many ways to control playback of audio/video files and streams. One

of this way is through a class called MediaPlayer.

• The android media framework provides a built in support for playing a variety of

common media types, such as audio or video. We have a multiple ways to play audio or

video but the most important component of media framework is MediaPlayer class.

• In android, by using MediaPlayer class we can access audio or video files from

application (raw) resources, standalone files in file system or from a data stream arriving

over a network connection and play audio or video files with the multiple playback

options such as play, pause, forward, backward, etc.

• we have to call a static Method create() of this class. This method returns an instance of

MediaPlayer class. Its syntax is as follows

Syntax:

MediaPlayer mPlayer = MediaPlayer.create(this,

R.raw.baitikochi_chuste);

• Once you have created the Mediaplayer object you can call some methods to start or stop

the music. These methods are listed below.

1. mediaPlayer.start();

2. mediaPlayer.pause();

• In order to start music from the beginning, you have to call reset() method. Its syntax is

given below.

mediaPlayer.reset();

• In case, if we want to play an audio from a URI that is locally available in the system, we

need to write the code like as shown below

Uri myUri = ....; // initialize Uri here

MediaPlayer mPlayer = new MediaPlayer();

mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

mPlayer.setDataSource(getApplicationContext(), myUri);

mPlayer.prepare();

mPlayer.start();

• STREAM_MUSIC- Used to identify the volume of audio streams for music playback

• If we want to play an audio from a URL via HTTP streaming, we need to write the code

like as shown below.

Page 25: Chapter 5 Intent

Example:

String url = "http://........"; // your URL here

MediaPlayer mPlayer = new MediaPlayer();

mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

mPlayer.setDataSource(url);

mPlayer.prepare(); // might take long! (for buffering, etc)

mPlayer.start();

• Methods of media player class:

Method Description

public boolean isLooping() checks if the player is looping or non-looping.

Method Description

public void setDataSource(String

path)

sets the data source (file path or http

url) to use.

public void prepare() prepares the player for playback

synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops the playback.

public void pause() it pauses the playback.

public boolean isPlaying() checks if media player is playing.

public void seekTo(int millis) seeks to specified time in miliseconds.

public void setLooping(boolean

looping)

sets the player for looping or non-

looping.

Page 26: Chapter 5 Intent

public void selectTrack(int index) it selects a track for the specified index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.

public void setVolume(float

leftVolume,float rightVolume)

sets the volume on this player.

• Video Player: In android, by using VideoView component and MediaController class we can easily

implement the video player in android applications to play the videos with multiple

playback options, such as play, pause, forward, backward, etc.

Example:

VideoView videoView = (VideoView)findViewById(R.id.vdVw);

MediaController mediaController= new MediaController(this);

mediaController.setAnchorView(videoView);

Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" +

R.raw.video1);

videoView.setMediaController(mediaController);

videoView.setVideoURI(uri);

videoView.requestFocus();

videoView.start();

• Methods of video player:

Method Description

Page 27: Chapter 5 Intent

setMediaController() It is used to set the media controller to

videoview.

setVideoURI() It is used to set the path of video file.

pause() It is used to pause the video playing.

stopPlayback() it is used to stop the video playing.

seekTo(position) It is used to move video to particular

position in milliseconds.

resume() It is used to resume the video playing.

start() It is used to start playing the audio /

video.

stopPlayback() It is used to stop playing the audio /

video.

• Text to Speech: Text to speech (TTS) makes an android device read the text and convert it to

audio out via the speaker. Android TTS supports multiple languages. TTS is a simple but

powerful feature. It can also be effectively used in mobile APPs dedicated to visually

impaired people or in educational app for kids or can be used in pronunciation learning

app, etc. These are some of the ways you can use TTS. Using TextToSpeech enhances

interaction between the user and the mobile application.

• Generally, the android TextToSpeech instance can only be used to synthesize text once it

has completed its initialization so implement TextToSpeech.OnInitListener to notify

the completion of initialization.

• During the initialization, we can set the audio pitch rate, audio speed, type of language to

speak, etc. based on our requirements.

• OnInitListener-Interface definition of a callback to be invoked indicating the completion

of the TextToSpeech engine initialization.

• TextToSpeech needs to be initialized first. For this, you need to implement

the TextToSpeech.OnInitListener interface and override the method: onInit

TextToSpeech tts = new TextToSpeech(this, this);

public TextToSpeech (Context context, TextToSpeech.OnInitListener listener)

Page 28: Chapter 5 Intent

• How to speak the text?

tts.speak(text, TextToSpeech.QUEUE_FLUSH, null, null);

– The first parameter is the text that would be spoken.

– The second parameter defines that the previous input is flushed so as to begin a

clean slate. Alternatively, we can use QUEUE_ADD to add the current text to the

speech.

– The third parameter is the bundle that is passed.

– Fourth is the utterance id string.

• OnUtteranceProgressListener is used to listen for the tts events: start,

done, error

• setLanguage()- CANADA_FRENCH, GERMANY, ITALY, JAPAN, CHINA

– ttobj.setLanguage(Locale.UK);

• Once you have set the language, you can call speak method of the class to speak the text.

ttobj.speak(toSpeak, TextToSpeech.QUEUE_FLUSH, null);

• In this method, we check whether the feature is available on our device or not.

@Override public void onInit(int status)

{

if (status == TextToSpeech.SUCCESS)

{

int result = tts.setLanguage(Locale.US);

if (result == TextToSpeech.LANG_MISSING_DATA || result ==

TextToSpeech.LANG_NOT_SUPPORTED)

{ Toast.makeText(getApplicationContext(), "Language not supported",

Toast.LENGTH_SHORT).show(); } else { //Disable the button if any. } } else {

Toast.makeText(getApplicationContext(), "Init failed", Toast.LENGTH_SHORT).show(); }

}

Methods Of text To Speech:

Sr.No Method & description

Page 29: Chapter 5 Intent

1 addSpeech(String text, String filename)

This method adds a mapping between a string of text and a sound file.

2 getLanguage()

This method returns a Locale instance describing the language.

3 isSpeaking()

This method checks whether the TextToSpeech engine is busy speaking.

4 setPitch(float pitch)

This method sets the speech pitch for the TextToSpeech engine.

5 setSpeechRate(float speechRate)

This method sets the speech rate.

6 shutdown()

This method releases the resources used by the TextToSpeech engine.

7 stop()

This method stop the speak.

Contants-

• ERROR-Denotes a generic operation failure.

• ERROR_SERVICE-Denotes a failure of a TTS service.

• LANG_AVAILABLE-Denotes the language is available for the language by the locale

• LANG_COUNTRY_AVAILABLE-Denotes the language is available for the language

and country specified by the locale

• LANG_MISSING_DATA-Denotes the language data is missing.

• LANG_NOT_SUPPORTED-Denotes the language is not supported.

• SUCCESS-Denotes a successful operation.

• QUEUE_FLUSH-Queue mode where all entries in the playback queue (media to be

played and text to be synthesized) are dropped and replaced by the new entry.

Page 30: Chapter 5 Intent

• STOPPED-Denotes a stop requested by a client.

Sensors

• Generally, most of the android devices have a built-in sensors to measure motion,

orientation and various environmental conditions.

• Most of the android devices have built-in sensors that measure motion, orientation, and

various environmental condition. The android platform supports three broad categories of

sensors.

– Motion Sensors

– Environmental sensors

– Position sensors

• Motion Sensors-These sensors are useful to measure acceleration forces and rotational

forces along three axes. This category includes accelerometers, gravity sensors,

gyroscopes, and rotational vector sensors.

• Environmental Sensors- These sensors are useful to measure various environmental

parameters, such as ambient air temperature and pressure, illumination, and humidity.

This category includes barometers, photometers, and thermometers.

• Position Sensors- These sensors are useful to measure the physical position of a device.

This category includes orientation sensors and magnetometers.

Android provided a framework called sensor framework to access all the sensors

available on device and to get all the raw sensor data. The sensor framework provided a wide

variety of sensor related tasks. For example, by using sensor framework we can perform

following things

• It lists all the available sensors on the device

• It determine the capabilities of each sensor, such as its maximum range, manufacturer,

power requirements, and resolution.

• It can acquire raw sensor data and define the minimum rate at which you acquire sensor

data.

• Register and unregister sensor event listeners that monitor sensor changes.

Page 31: Chapter 5 Intent

The Android sensor framework will allow us to access many type of sensors, some of

these sensors are hardware-based and some are software-based. The Hardware-based sensors

are physical components built on the handset or tablet device and Software-based sensors are not

a physical devices but they mimic Hardware-based sensors.

Classes –

Class Description

SensorManager By using this class we can create an instance of sensor

service and this class provides a various methods for

accessing and listing sensors, registering and unregistering

sensor event listeners and acquiring orientation information.

Sensor By using this class we can create an instance of a specific

sensor and this class provides a various methods that let you

determine the sensor's capabilities.

SensorEvent The system uses this class to create a sensor event object

and it provides the raw sensor data, type of sensor that

generated the event, accuracy of the data, and the timestamp

for the event.

SensorEventListener We can use this interface to create two callback methods

that receive notifications (sensor events) when sensor values

change or when sensor accuracy changes.

SensorManager lets you access the device's sensors.

• The android.hardware.SensorManager class provides methods :

– to get sensor instance,

– to access and list sensors,

– to register and unregister sensor listeners etc.

• You can get the instance of SensorManager by calling the method getSystemService()

and passing the SENSOR_SERVICE constant in it.

SensorManager sm = (SensorManager)getSystemService(SENSOR_SERVICE);

Page 32: Chapter 5 Intent

• class provides methods :

-to get sensor instance,

-to access and list sensors,

-to register and unregister sensor listeners etc.

• public int getSensors ()

• getSensorList()

public List<Sensor> getSensorList (int type)

- Use this method to get the list of available sensors of a certain type. Make multiple calls

to get sensors of different types or use Sensor.TYPE_ALL to get all the sensors.

• registerListener

public boolean registerListener (SensorEventListener listener, Sensor sensor, int

samplingPeriodUs)

The rate sensor events are delivered at

• unregisterListener

public boolean unregisterListener (SensorEventListener listener, Sensor sensor)

Sensor Class

The android.hardware.Sensor class provides methods to get information of the sensor such as

sensor name, sensor type, sensor resolution, sensor type etc.

The Sensor class defines several constants for accessing the different sensors

Sensor Type Description Common

Uses

Page 33: Chapter 5 Intent

TYPE_ACCELEROMETER Hardware Measures the acceleration

force in m/s2 that is

applied to a device on all

three physical axes (x, y,

and z), including the

force of gravity.

Motion

detection

(shake, tilt,

etc.).

TYPE_AMBIENT_TEMPERATURE Hardware Measures the ambient

room temperature in

degrees Celsius (°C). See

note below.

Monitoring

air

temperatures.

TYPE_GRAVITY Software

or

Hardware

Measures the force of

gravity in m/s2 that is

applied to a device on all

three physical axes (x, y,

z).

Motion

detection

(shake, tilt,

etc.).

Page 34: Chapter 5 Intent

TYPE_GYROSCOPE Hardware Measures a device's rate of rotation in rad/s

around each of the three physical axes (x, y, and

z).

Rotation

detection

(spin, turn,

etc.).

TYPE_LIGHT Hardware Measures the ambient light level (illumination)

in lx.

Controlling

screen

brightness.

TYPE_LINEAR_ACCELERATION Software

or

Hardware

Measures the acceleration force in m/s2 that is

applied to a device on all three physical axes (x,

y, and z), excluding the force of gravity.

Monitoring

acceleration

along a

single axis.

TYPE_MAGNETIC_FIELD Hardware Measures the ambient geomagnetic field for all

three physical axes (x, y, z) in μT.

Creating a

compass.

TYPE_ORIENTATION Software Measures degrees of rotation that a device

makes around all three physical axes (x, y, z).

As of API level 3 you can obtain the inclination

matrix and rotation matrix for a device by using

the gravity sensor and the geomagnetic field

sensor in conjunction with

the getRotationMatrix() method.

Determining

device

position.

TYPE_PRESSURE Hardware Measures the ambient air pressure in hPa or

mbar.

Monitoring

air pressure

changes.

TYPE_PROXIMITY Hardware Measures the proximity of an object in cm

relative to the view screen of a device. This

sensor is typically used to determine whether a

handset is being held up to a person's ear.

Phone

position

during a call.

TYPE_RELATIVE_HUMIDITY Hardware Measures the relative ambient humidity in

percent (%).

Monitoring

dew point,

absolute, and

relative

humidity.

TYPE_ROTATION_VECTOR Software

or

Hardware

Measures the orientation of a device by

providing the three elements of the device's

rotation vector.

Motion

detection and

rotation

detection.

Page 35: Chapter 5 Intent

Sensor Class:

You can access the sensor via the sensorManager.getDefaultSensor() method, which takes the

sensor type and the delay defined as constants on SensorManager as parameters.

Sensor light;

light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

SensorEvent class-

Its instance is created by the system. It provides information about the sensor.

SensorEventListener interface-

TYPE_TEMPERATURE Hardware Measures the temperature of the device in

degrees Celsius (°C). This sensor

implementation varies across devices and this

sensor was replaced with

the TYPE_AMBIENT_TEMPERATURE sensor

in API Level 14

Monitoring

temperatures.

Page 36: Chapter 5 Intent

It provides two call back methods to get information when sensor values (x,y and z)

change or sensor accuracy changes

Public and abstract methods Description

void onAccuracyChanged(Sensor sensor,

int accuracy)

it is called when sensor accuracy is changed.

void onSensorChanged(SensorEvent event) it is called when sensor values are changed.

Steps:

1. Android provides SensorManager and Sensor classes to use the sensors in our

application. In order to use sensors, first thing you need to do is to instantiate the object

of SensorManager class. It can be achieved as follows.

SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);

2. The next thing you need to do is to instantiate the object of Sensor class by calling the

getDefaultSensor() method of the SensorManager class. Its syntax is given below −

Sensor light;

light = sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);

3. Once that sensor is declared , you need to register its listener and override two methods

which are onAccuracyChanged and onSensorChanged. Its syntax is as follows −

sMgr.registerListener(this, light,SensorManager.SENSOR_DELAY_NORMAL);

public void onAccuracyChanged(Sensor sensor, int accuracy)

{ }

public void onSensorChanged(SensorEvent event) { }

Page 37: Chapter 5 Intent

SQLite Database:

SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in

with built in SQLite database implementation.

SQLite supports all the relational database features. In order to access this database, you don't

need to establish any kind of connections for it like JDBC,ODBC e.t.c

Database - Package

The main package is android.database.sqlite that contains the classes to manage your own

databases

Database - Creation

In order to create a database you just need to call this method openOrCreateDatabase with your

database name and mode as a parameter. It returns an instance of SQLite database which you

have to receive in your own object.Its syntax is given below

SQLiteDatabase mydatabase = openOrCreateDatabase("your database

name",MODE_PRIVATE,null);

Page 38: Chapter 5 Intent

Apart from this , there are other functions available in the database package , that does this job.

They are listed below

Sr.No Method & Description

1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags,

DatabaseErrorHandler errorHandler)

This method only opens the existing database with the appropriate flag mode. The common flags mode

could be OPEN_READWRITE OPEN_READONLY

2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)

It is similar to the above method as it also opens the existing database but it does not define any handler to

handle the errors of databases

3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)

It not only opens but create the database if it not exists. This method is equivalent to openDatabase method.

4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)

This method is similar to above method but it takes the File object as a path rather then a string. It is

equivalent to file.getPath()

Database - Insertion

we can create table or insert data into table using execSQL method defined in SQLiteDatabase

class. Its syntax is given below

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username

VARCHAR,Password VARCHAR);");

mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('admin','admin');");

This will insert some values into our table in our database. Another method that also does the

same job but take some additional parameter is given below

Sr.No Method & Description

1 execSQL(String sql, Object[] bindArgs)

This method not only insert data , but also used to update or modify already existing data in database

using bind arguments

Page 39: Chapter 5 Intent

Database - Fetching

We can retrieve anything from database using an object of the Cursor class. We will call a method

of this class called rawQuery and it will return a resultset with the cursor pointing to the table.

We can move the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from TutorialsPoint",null);

resultSet.moveToFirst();

String username = resultSet.getString(0);

String password = resultSet.getString(1);

There are other functions available in the Cursor class that allows us to effectively retrieve the

data. That includes

Sr.No Method & Description

1 getColumnCount()

This method return the total number of columns of the table.

2 getColumnIndex(String columnName)

This method returns the index number of a column by specifying the name of the column

3 getColumnName(int columnIndex)

This method returns the name of the column by specifying the index of the column

4 getColumnNames()

This method returns the array of all the column names of the table.

5 getCount()

This method returns the total number of rows in the cursor

6 getPosition()

This method returns the current position of the cursor in the table

7 isClosed()

This method returns true if the cursor is closed and return false otherwise

Page 40: Chapter 5 Intent

Database - Helper class

For managing all the operations related to the database , an helper class has been given and is

called SQLiteOpenHelper. It automatically manages the creation and update of the database. Its

syntax is given below

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(){

super(context,DATABASE_NAME,null,1);

}

public void onCreate(SQLiteDatabase db) {}

public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}

}

Example

Here is an example demonstrating the use of SQLite Database. It creates a basic contacts

applications that allows insertion, deletion and modification of contacts.

To experiment with this example, you need to run this on an actual device on which camera is

supported.

Steps Description

1 You will use Android studio to create an Android application under a package

com.example.sairamkrishna.myapplication.

2 Modify src/MainActivity.java file to get references of all the XML components and populate the contacts

on listView.

3 Create new src/DBHelper.java that will manage the database work

4 Create a new Activity as DisplayContact.java that will display the contact on the screen

5 Modify the res/layout/activity_main to add respective XML components

6 Modify the res/layout/activity_display_contact.xml to add respective XML components

Page 41: Chapter 5 Intent

7 Modify the res/values/string.xml to add necessary string components

8 Modify the res/menu/display_contact.xml to add necessary menu components

9 Create a new menu as res/menu/mainmenu.xml to add the insert contact option

10 Run the application and choose a running android device and install the application on it and verify the

results.

Constructors of SQLiteOpenHelper class

There are two constructors of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name,

SQLiteDatabase.CursorFactory factory, int version)

creates an object for creating, opening

and managing the database.

SQLiteOpenHelper(Context context, String name,

SQLiteDatabase.CursorFactory factory, int version,

DatabaseErrorHandler errorHandler)

creates an object for creating, opening

and managing the database. It

specifies the error handler.

Methods of SQLiteOpenHelper class

There are many methods in SQLiteOpenHelper class. Some of them are as follows:

Method Description

Page 42: Chapter 5 Intent

public abstract void onCreate(SQLiteDatabase db) called only once when database is

created for the first time.

public abstract void onUpgrade(SQLiteDatabase db, int

oldVersion, int newVersion)

called when database needs to be

upgraded.

public synchronized void close () closes the database object.

public void onDowngrade(SQLiteDatabase db, int oldVersion,

int newVersion)

called when database needs to be

downgraded.

SQLiteDatabase class

It contains methods to be performed on sqlite database such as create, update, delete, select etc.

Methods of SQLiteDatabase class

There are many methods in SQLiteDatabase class. Some of them are as follows:

Method Description

void execSQL(String sql) executes the sql query not select query.

long insert(String table, String

nullColumnHack, ContentValues

values)

inserts a record on the database. The table specifies the table

name, nullColumnHack doesn't allow completely null values.

If second argument is null, android will store null values if

values are empty. The third argument specifies the values to

be stored.

Page 43: Chapter 5 Intent

int update(String table, ContentValues

values, String whereClause, String[]

whereArgs)

updates a row.

Cursor query(String table, String[]

columns, String selection, String[]

selectionArgs, String groupBy, String

having, String orderBy)

returns a cursor over the resultset.

Page 44: Chapter 5 Intent

Chapter 6 [20]

Security and Application Deployment

In android, we can send SMS from our android application in two ways

By using SmsManager class

By using an implicit Intent

1. SmsManager class-

If we use SMSManager API, it will directly send SMS from our application.

SMSManager class is used to send sms

Sr.No. Method & Description

1 ArrayList<String> divideMessage(String text)

This method divides a message text into several fragments, none bigger than the

maximum SMS message size.

2 static SmsManager getDefault()

This method is used to get the default instance of the SmsManager

3 void sendDataMessage(String destinationAddress, String scAddress, short

destinationPort, byte[] data, PendingIntent sentIntent, PendingIntent

deliveryIntent)

This method is used to send a data based SMS to a specific application port.

4 void sendMultipartTextMessage(String destinationAddress, String scAddress,

ArrayList<String> parts, ArrayList<PendingIntent> sentIntents,

ArrayList<PendingIntent> deliveryIntents)

Send a multi-part text based SMS.

Page 45: Chapter 5 Intent

5 void sendTextMessage(String destinationAddress, String scAddress, String

text, PendingIntent sentIntent, PendingIntent deliveryIntent)

Send a text based SMS.

SmsManager = SmsManager.getDefault();

smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);

SMSManager API required SEND_SMS permission in our android manifest

to send SMS. Following is the code snippet to set SEND_SMS permissions in

manifest file.

<uses-permission android:name="android.permission.SEND_SMS"/>

In android, we can easily send an email from our android application using existing

email clients such as GMAIL, Outlook, etc. instead of building an email client from

scratch.

Generally, the Intent object in android with proper action (ACTION_SEND)

and data will help us to launch the available email clients to send an email in our

application.

In android, Intent is a messaging object which is used to request an action

from another app component such as activities, services, broadcast receivers,

and content providers.

To send an email using the Intent object in android application, we need to write the

code as shown below.

Intent it = new Intent(Intent.ACTION_SEND);

it.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});

it.putExtra(Intent.EXTRA_SUBJECT, "Welcome to Tutlane");

it.putExtra(Intent.EXTRA_TEXT, "Hi Guest, Welcome to Tutlane Tutorial

Site");

it.setType("message/rfc822");

Page 46: Chapter 5 Intent

To send an email from your application, you don’t have to implement an email client from the beginning, but you can use an existing one like the default Email app provided from Android, Gmail, Outlook, K-9 Mail etc. For this purpose, we need to write an Activity that launches an email client, using an implicit Intent with the right action and data. In this example, we are going to send an email from our app by using an Intent object that launches existing email clients.

Following section explains different parts of our Intent object required to send an email.

Intent Object - Action to send Email

You will use ACTION_SEND action to launch an email client installed on your Android device. Following is simple syntax to create an intent with ACTION_SEND action.

Intent emailIntent = new Intent(Intent.ACTION_SEND);

Intent Object - Data/Type to send Email

Sr.No. Extra Data & Description

1 EXTRA_BCC

A String[] holding e-mail addresses that should be blind carbon copied.

2 EXTRA_CC

A String[] holding e-mail addresses that should be carbon copied.

3 EXTRA_EMAIL

A String[] holding e-mail addresses that should be delivered to.

4 EXTRA_HTML_TEXT

A constant String that is associated with the Intent, used with ACTION_SEND to supply an alternative to EXTRA_TEXT as HTML formatted text.

5 EXTRA_SUBJECT

A constant string holding the desired subject line of a message.

Page 47: Chapter 5 Intent

To send an email you need to specify mailto: as URI using setData() method and data type will be to text/plain using setType() method as follows −

emailIntent.setData(Uri.parse("mailto:"));

emailIntent.setType("text/plain");

6 EXTRA_TEXT

A constant CharSequence that is associated with the Intent, used with ACTION_SEND to supply the literal data to be sent.

7 EXTRA_TITLE

A CharSequence dialog title to provide to the user when used with a ACTION_CHOOSER

Page 48: Chapter 5 Intent

Intent Object - Extra to send Email

Android has built-in support to add TO, SUBJECT, CC, TEXT etc. fields which

can be attached to the intent before sending the intent to a target email client. You

can use following extra fields in your email

For below example code is present in folder email refer all files

Page 49: Chapter 5 Intent

By Intent

You can use Android Intent to send SMS by calling built-in SMS functionality

of the Android. Following section explains different parts of our Intent object

required to send an SMS.

Intent Object - Action to send SMS

You will use ACTION_VIEW action to launch an SMS client installed on

your Android device. Following is simple syntax to create an intent with

ACTION_VIEW action.

Intent smsIntent = new Intent(Intent.ACTION_VIEW);

Intent Object - Data/Type to send SMS

To send an SMS you need to specify smsto: as URI using setData() method

and data type will be to vnd.android-dir/mms-sms using setType() method as

follows −

smsIntent.setData(Uri.parse("smsto:"));

smsIntent.setType("vnd.android-dir/mms-sms");

Intent Object - Extra to send SMS

Android has built-in support to add phone number and text message to send an SMS

as follows −

smsIntent.putExtra("address" , new

String("0123456789;3393993300")); smsIntent.putExtra("sms_body" ,

"Test SMS to Angilla");

Page 50: Chapter 5 Intent

Android Google Maps

Android provides facility to integrate Google map in our application. Google

map displays your current location, navigate location direction, search location etc.

We can also customize Google map according to our requirement.

• Types of Google Maps

1. Normal: This type of map displays typical road map, natural features like

river and some features build by humans.

2. Hybrid: This type of map displays satellite photograph data with typical

road maps. It also displays road and feature labels.

3. Satellite: Satellite type displays satellite photograph data, but doesn't

display road and feature labels.

4. Terrain: This type displays photographic data. This includes colors,

contour lines and labels and perspective shading.

5. None: This type displays an empty grid with no tiles loaded.

Page 51: Chapter 5 Intent

Google API

The Google Maps Android API consists of a core set of classes that combine to

provide mapping capabilities in Android applications. The key elements of a map

are as follows:

• GoogleMap – The main class of the Google Maps Android API. This class is

responsible for downloading and displaying map tiles and for displaying and

responding to map controls. The GoogleMap object is not created directly by

the application but is instead created when MapView or MapFragment

instances are created. A reference to the GoogleMap object can be obtained

within application code via a call to the getMap() method of a MapView,

MapFragment or SupportMapFragment instance.

• MapView - A subclass of the View class, this class provides the view canvas

onto which the map is drawn by the GoogleMap object, allowing a map to be

placed in the user interface layout of an activity.

• SupportMapFragment – A subclass of the Fragment class, this class allows

a map to be placed within a Fragment in an Android layout.

• Marker – The purpose of the Marker class is to allow locations to be marked

on a map. Markers are added to a map by obtaining a reference to the

GoogleMap object associated with a map and then making a call to the

addMarker () method of that object instance. The position of a marker is

defined via Longitude and Latitude. Markers can be configured in a number

of ways, including specifying a title, text and an icon. Markers may also be

made to be “draggable”, allowing the user to move the marker to different

positions on a map.

• Shapes – The drawing of lines and shapes on a map is achieved through the

use of the Polyline, Polygon and Circle classes.

• UiSettings – The UiSettings class provides a level of control from within an

application of which user interface controls appear on a map. Using this class,

for example, the application can control whether or not the zoom, current

location and compass controls appear on a map.

Displaying the Map

Page 52: Chapter 5 Intent

To get hold of the GoogleMap object in our MainActivity class we need to

implement the OnMapReadyCallback interface and override

the onMapReady callback method.

• Syntax of different types of map

googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);

googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Methods Description

addCircle(CircleOptions options) This method add circle to map.

addPolygon(PolygonOptions options) This method add polygon to map.

addTileOverlay(TileOverlayOptions options) This method add tile overlay to the map.

animateCamera(CameraUpdate update) This method moves the map according to the

update with an animation.

clear() This method removes everything from the

map.

getMyLocation() This method returns the currently displayed

user location.

moveCamera(CameraUpdate update) This method reposition the camera

according to the instructions defined in the

update.

Page 53: Chapter 5 Intent

setTrafficEnabled(boolean enabled) This method set the traffic layer on or off.

snapshot(GoogleMap.SnapshotReadyCallback

callback)

This method takes a snapshot of the map.

stopAnimation() This method stops the camera animation if

there is any progress.

Step: Now open google_maps_api.xml (debug) in values folder

Page 54: Chapter 5 Intent

Step : Now open activity_maps.xml and add a fragment code in it

• Here add a fragment element to the activity’s layout file to define

a Fragment object. In this element, set the android:name attribute

to “com.google.android.gms.maps.MapFragment”. This automatically

attaches a MapFragment to the activity. The following layout file contains

a fragment element:

<fragment

android:id="@+id/map"

android:name="com.google.android.gms.maps.SupportMapFragment"

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:map="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent" android:layout_height="match_parent"

tools:context="com.abhiandroid.GoogleMaps.googlemaps.MapsActivity"/>

Page 55: Chapter 5 Intent

• INTERNET – To determine if we are connected to Internet or not.

ACCESS_FINE_LOCATION – To determine user’s location using GPS. It

will give us precise location.

<uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-permission android:name="android.permission.INTERNET"/>

Step : Now we will code MapsActivity.java file for inserting callbacks in Google

Maps

• -OnMapReadyCallback:

• This callback is called when the map is ready to be used

@Override

public void onMapReady(GoogleMap googleMap) { }

This callback is called whenever device is connected and disconnected and

implement onConnected() and onConnectionSuspended() functions.

//When the connect request has successfully completed @Override

public void onConnected(Bundle bundle) { }

//Called when the client is temporarily in a disconnected state. @Override

public void onConnectionSuspended(int i) { }

Page 56: Chapter 5 Intent

Displaying zoom control

You can also enable or disable the zoom gestures in the map by calling the

setZoomControlsEnabled(boolean) method.

UiSettings class- Settings for the user interface of a GoogleMap. To obtain this

interface, call getUiSettings().

UiSettings uiSettings = map.getUiSettings();

uiSettings.setZoomGesturesEnabled(true);

Or

map.getUiSettings().setZoomGesturesEnabled(true);

Page 57: Chapter 5 Intent

You can place a maker with some text over it displaying your location on the map.

It can be done by via addMarker() method. Its syntax is given below −

final LatLng TutorialsPoint = new LatLng(21 , 57);

Marker TP = googleMap.addMarker(new MarkerOptions()

.position(TutorialsPoint).title("TutorialsPoint"));

Geocoder and Reverse GeoCoder

A class for handling geocoding and reverse geocoding. Geocoding is the process of

transforming a street address or other description of a location into a (latitude,

longitude) coordinate. Reverse geocoding is the process of transforming a (latitude,

longitude) coordinate into a (partial) address. The amount of detail in a reverse

geocoded location description may vary, for example one might contain the full

street address of the closest building, while another might contain only a city name

and postal code

Geocoder

Android Geocoder class is used for Geocoding as well as Reverse Geocoding.

Geocoding refers to transforming street address or any address into latitude and

longitude. Reverse Geocoding refers to transforming latitude and longitude into its

corresponding street address.

Address class helps in fetching the street address, locality, sub-locality, city, country,

landmark etc. features of the location.

Page 58: Chapter 5 Intent

Geocoding is the process of converting addresses (like a street address) into

geographic coordinates (like latitude and longitude), which you can use to place

markers on a map, or position the map.

Reverse geocoding is the process of converting geographic coordinates into a

human-readable address.

Geocoding

Geocoding is the process of converting the addresses (postal address) into geo

coordinates as latitude and longitude. Reverse geocoding is converting a geo

coordinate latitude and longitude to an address. In this tutorial we will be doing

reverse geo coding and get the addresses of the passed coordinates.

Methods of Geocoder class

1.List<Address> getFromLocation(double latitude, double longitude, int

maxResults):- This method returns an array of Address which specifies the

surrounding latitude and longitude.

2.List<Address> getFromLocationName(String location, int results, double

leftLatitude, double leftLongitude, double rightLatitude, double

rightLongitude):- This method returns an array of Address which describes the

given location such as place, an address, etc.

Page 59: Chapter 5 Intent

3.List<Address> getFromLocationName(String location, int results): This

method returns an array of Address which describes te given location such as place,

an address, etc.

4.static boolean isPresent(): This method returns true if the methods

getFromLocation() and getFromLocationName() are implemented.

Location class Methods

A class representing an Address, i.e, a set of Strings describing a location.

Methods of Android.Location.address class-

• public String getCountryCode ()- Returns the country code of the address, for

example "US", or null if it is unknown.

• public String getCountryName ()-Returns the localized country name of the

address, for example "Iceland", or null if it is unknown.

• public double getLatitude ()- Returns the latitude of the address if known

• public String getLocality ()-Returns the locality of the address, for example

"Mountain View", or null if it is unknown.

• public double getLongitude ()- Returns the longitude of the address if known.

• public String getPhone ()- Returns the phone number of the address if known,

or null if it is unknown.

• public String getPostalCode ()Returns the postal code of the address, for

example "94110", or null if it is unknown.

• public String getPremises ()Returns the premises of the address, or null if it is

unknown.

• public boolean hasLatitude ()-Returns true if a latitude has been assigned to

this Address, false otherwise.

Page 60: Chapter 5 Intent

• public boolean hasLongitude ()-Returns true if a longitude has been assigned

to this Address, false otherwise.

• 11.public void setAddressLine (int index, String line)- Sets the line of the

address numbered by index (starting at 0) to the given String, which may be

null.

• public void setCountryCode (String countryCode)- Sets the country code of

the address to the given String, which may be null.

• public void setCountryName (String countryName)- Sets the country name of

the address to the given String, which may be null.

• public void setLatitude (double latitude)- Sets the latitude associated with this

address.

• public void setLocality (String locality)- Sets the locality of the address to the

given String, which may be null.

• public void setLongitude (double longitude)-Sets the longitude associated

with this address.

• public void setPhone (String phone)-Sets the phone number associated with

this address.

• public void setPostalCode (String postalCode)-Sets the postal code of the

address to the given String, which may be null.

• public void setPremises (String premises)-Sets the premises of the address to

the given String, which may be null.

Page 61: Chapter 5 Intent

Android Reverse Geocoding

Step1: Define Permissions

We need location access permission to find the latitude and longitude of the Android

device. Following two lines are the key to give permission to access the location.

<uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.INTERNET" />

XML Code:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="android.javapapers.com.androidgeocodelocation" >

<uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.INTERNET" />

<application

android:allowBackup="true"

android:icon="@drawable/ic_launcher"

android:label="@string/app_name"

android:theme="@style/AppTheme" >

<activity

android:name=".MyActivity"

android:label="@string/app_name" >

<intent-filter>

Page 62: Chapter 5 Intent

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

Step 2: Accessing the Geo Location for Lat and Long

Following class is the key element in accessing the latitude and longitude of the

Android device. It implements the LocationListener and gets the location coordinate

updates. We have designed our requirement not to be a continous update for location.

On demand we will get the location coordinates.

Step 3: Reverse Geocoding to get Location Address

Following class is the key element for reverse geocoding to get the address for the

passed latitude and longitude coordinates. We access the Geocoder Google API for

reverse geocoding and get every line of address like street, city, pin / zip code and

etc.

LocationAddress.java

package android.javapapers.com.androidgeocodelocation;

import android.content.Context;

import android.location.Address;

import android.location.Geocoder;

import android.os.Bundle;

import android.os.Handler;

Page 63: Chapter 5 Intent

import android.os.Message;

import android.util.Log;

import java.io.IOException;

import java.util.List;

import java.util.Locale;

public class LocationAddress {

private static final String TAG = "LocationAddress";

public static void getAddressFromLocation(final double latitude, final double

longitude,

final Context context, final Handler handler) {

Thread thread = new Thread() {

@Override

public void run() {

Geocoder geocoder = new Geocoder(context, Locale.getDefault());

String result = null;

try {

List<Address> addressList = geocoder.getFromLocation(

latitude, longitude, 1);

if (addressList != null && addressList.size() > 0) {

Address address = addressList.get(0);

StringBuilder sb = new StringBuilder();

for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {

sb.append(address.getAddressLine(i)).append("\n");

Page 64: Chapter 5 Intent

}

sb.append(address.getLocality()).append("\n");

sb.append(address.getPostalCode()).append("\n");

sb.append(address.getCountryName());

result = sb.toString();

}

} catch (IOException e) {

Log.e(TAG, "Unable connect to Geocoder", e);

} finally {

Message = Message.obtain();

message.setTarget(handler);

if (result != null) {

message.what = 1;

Bundle bundle = new Bundle();

result = "Latitude: " + latitude + " Longitude: " + longitude +

"\n\nAddress:\n" + result;

bundle.putString("address", result);

message.setData(bundle);

} else {

message.what = 1;

Bundle bundle = new Bundle();

result = "Latitude: " + latitude + " Longitude: " + longitude +

"\n Unable to get address for this lat-long.";

bundle.putString("address", result);

message.setData(bundle);

Page 65: Chapter 5 Intent

}

message.sendToTarget();

}

}

};

thread.start();

}

}

Step 4: Android UI

How these pieces fit together is with the following Android activity.

MyActivity.java

package android.javapapers.com.androidgeocodelocation;

import android.app.Activity;

import android.app.AlertDialog;

import android.content.DialogInterface;

import android.content.Intent;

import android.location.Location;

import android.location.LocationManager;

import android.os.Bundle;

import android.os.Handler;

import android.os.Message;

import android.provider.Settings;

import android.view.View;

import android.widget.Button;

Page 66: Chapter 5 Intent

import android.widget.TextView;

public class MyActivity extends Activity {

Button btnGPSShowLocation;

Button btnShowAddress;

TextView tvAddress;

AppLocationService appLocationService;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_my);

tvAddress = (TextView) findViewById(R.id.tvAddress);

appLocationService = new AppLocationService(

MyActivity.this);

btnGPSShowLocation = (Button) findViewById(R.id.btnGPSShowLocation);

btnGPSShowLocation.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

Location gpsLocation = appLocationService

.getLocation(LocationManager.GPS_PROVIDER);

if (gpsLocation != null) {

Page 67: Chapter 5 Intent

double latitude = gpsLocation.getLatitude();

double longitude = gpsLocation.getLongitude();

String result = "Latitude: " + gpsLocation.getLatitude() +

" Longitude: " + gpsLocation.getLongitude();

tvAddress.setText(result);

} else {

showSettingsAlert();

}

}

});

btnShowAddress = (Button) findViewById(R.id.btnShowAddress);

btnShowAddress.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View arg0) {

Location location = appLocationService

.getLocation(LocationManager.GPS_PROVIDER);

//you can hard-code the lat & long if you have issues with getting it

//remove the below if-condition and use the following couple of lines

//double latitude = 37.422005;

//double longitude = -122.084095

if (location != null) {

Page 68: Chapter 5 Intent

double latitude = location.getLatitude();

double longitude = location.getLongitude();

LocationAddress locationAddress = new LocationAddress();

locationAddress.getAddressFromLocation(latitude, longitude,

getApplicationContext(), new GeocoderHandler());

} else {

showSettingsAlert();

}

}

});

}

public void showSettingsAlert() {

AlertDialog.Builder alertDialog = new AlertDialog.Builder(

MyActivity.this);

alertDialog.setTitle("SETTINGS");

alertDialog.setMessage("Enable Location Provider! Go to settings menu?");

alertDialog.setPositiveButton("Settings",

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

Intent intent = new Intent(

Settings.ACTION_LOCATION_SOURCE_SETTINGS);

MyActivity.this.startActivity(intent);

Page 69: Chapter 5 Intent

}

});

alertDialog.setNegativeButton("Cancel",

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

dialog.cancel();

}

});

alertDialog.show();

}

private class GeocoderHandler extends Handler {

@Override

public void handleMessage(Message message) {

String locationAddress;

switch (message.what) {

case 1:

Bundle bundle = message.getData();

locationAddress = bundle.getString("address");

break;

default:

locationAddress = null;

}

tvAddress.setText(locationAddress);

}

Page 70: Chapter 5 Intent

}

}

Android UI layout file to show the address and location

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:paddingBottom="@dimen/activity_vertical_margin"

tools:context=".MyActivity">

<TextView

android:text="@string/hello_world"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/textView" />

<Button

style="?android:attr/buttonStyleSmall"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Location"

android:id="@+id/btnGPSShowLocation"

Page 71: Chapter 5 Intent

android:layout_toEndOf="@+id/textView"

android:layout_marginTop="53dp"

android:layout_below="@+id/textView"

android:layout_alignParentStart="true" />

<Button

style="?android:attr/buttonStyleSmall"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Address"

android:id="@+id/btnShowAddress"

android:layout_toEndOf="@+id/tvAddress"

android:layout_below="@+id/btnGPSShowLocation"

android:layout_alignParentStart="true" />

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/tvAddress"

android:layout_alignParentBottom="true"

android:layout_marginBottom="134dp"

android:layout_alignParentEnd="true" />

</RelativeLayout>

Page 72: Chapter 5 Intent

Key Points for Geocoding

• Need Google API access and so remember to run in an emulator that is

configured for Google API.

• Remember to have the right permissions defined in the Mainfest.xml

• To test via an Android Emulator, we can use the DDMS and pass the latitude

and longitude using the ‘Emulator Control’.

Reverse Geo Coding

Android Geocoder class is used for Geocoding as well as Reverse

Geocoding. Geocoding refers to transforming street address or any address into

latitude and longitude. Reverse Geocoding refers to transforming latitude and

longitude into its corresponding street address.

Getting the location

LocationListener & Location-

The LocationListener interface, which is part of the Android Locations API is used

for receiving notifications from the LocationManager when the location has

changed. The LocationManager class provides access to the systems location

services.

The LocationListener class needs to implement the following methods.

• onLocationChanged(Location location) : Called when the location has

changed.

• onProviderDisabled(String provider) : Called when the provider is disabled

by the user.

• onProviderEnabled(String provider) : Called when the provider is enabled

by the user.

• onStatusChanged(String provider, int status, Bundle extras) : Called

when the provider status changes.

Page 73: Chapter 5 Intent

Location -

The Location object represents a geographic location which can consist of a

latitude, longitude, time stamp, and other information such as bearing, altitude and

velocity.

• double getLatitude()-Get the latitude, in degrees.

• double getLongitude()-Get the longitude, in degrees.

• boolean hasAltitude()-True if this location has an altitude.

• boolean hasBearing()-True if this location has a bearing.

• void reset()-Clears the contents of the location.

• void setAccuracy(float accuracy)-Set the estimated accuracy of this

location, meters.

• void setAltitude(double altitude)-Set the altitude, in meters above sea level.

Retriving the location

• void setBearing(float bearing)-Set the bearing, in degrees.

• void setLatitude(double latitude)-Set the latitude, in degrees.

• void setLongitude(double longitude)-Set the longitude, in degrees.

Access the location

• Provide permissions for receiving location update

To access current location information through location providers, we need

to set permissions with android manifest file.

<manifest ... >

<uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION" />

<uses-permission android:name="android.permission.

ACCESS_COARSE_LOCATION" />

<uses-permission android:name="android.permission.INTERNET" />

• </manifest>

Page 74: Chapter 5 Intent

ACCESS_COARSE_LOCATION is used when we use network location provider

for our Android app. But, ACCESS_FINE_LOCATION is providing permission for

both providers. INTERNET permission is must for the use of network provider.

Create LocationManager instance as reference to the location service

locationManager = (LocationManager)

getSystemService(Context.LOCATION_SERVICE);

requestLocationUpdates(String provider, long minTimeMs, float

minDistanceM, LocationListener listener)

Register for location updates from the given provider with the given arguments.

• Request current location from LocationManager

After creating the location service reference, location updates are requested

using requestLocationUpdates() method of LocationManager. For this function, we

need to send the type of location provider, number of seconds, distance and the

LocationListener object over which the location to be updated.

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,

0, this);

Page 75: Chapter 5 Intent
Page 76: Chapter 5 Intent

Monitoring the Location

Geofencing combines awareness of the user's current location with awareness of the

user's proximity to locations that may be of interest. To mark a location of interest,

you specify its latitude and longitude. To adjust the proximity for the location, you

add a radius. The latitude, longitude, and radius define a geofence, creating a circular

area, or fence, around the location of interest.

Set up for Geofence monitoring

The first step in requesting geofence monitoring is to request the necessary

permission. To use geofencing, your app must

request ACCESS_FINE_LOCATION. If your app targets Android 10 (API level 29)

or higher, your app must also request ACCESS_BACKGROUND_LOCATION.

To request the necessary permissions, add them as child elements of

the <manifest> element in your app manifest:

<uses-permission

android:name="android.permission.ACCESS_FINE_LOCATION"/>

Page 77: Chapter 5 Intent

<!-- Required if your app targets Android 10 (API level 29) or higher -->

<uses-permission

android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

If you want to use a BroadcastReceiver to listen for geofence transitions, add an

element specifying the service name. This element must be a child of

the <application> element:

<application

android:allowBackup="true">

...

<receiver android:name=".GeofenceBroadcastReceiver"/>

<application/>

To access the location APIs, you need to create an instance of the Geofencing

client. To learn how to connect your client:

Page 78: Chapter 5 Intent

Android security model

a) Threat Model

b) Android platform security model

1. Threat Model

Beyond its authorizations, data can be accessed and operated through a

Privilege application based on this attack Escalation - This attack is totally

different within various mobile platforms.

Mobile platforms is a targetable area to malware attacks because various mobile

platforms have powerful ability to store a large amount of data (sensitive)

Malicious - Based on the researches and articles Applications there are some of

the malware threats have been addressed such as by static and dynamic analysis

of application binaries, enhanced application installers, novel run-time privacy

Page 79: Chapter 5 Intent

frameworks and app store analysis tools. - Evaluate potential privacy and

security risks Risky In-App - An advertisement library is a part of Ad Libraries

the apps, that the app developers integrate it.

2. Android Platform Security Model:

The Android security model is primarily based on a sandbox and permission

mechanism. Each application is running in a specific Dalvik virtual machine with a

unique user ID assigned to it, which means the application code runs in isolation

from the code of all others applications. As a consequence, one application has not

granted access to other applications’ files.

Android application has been signed with a certificate with a private key Know the

owner of the application is unique. This allows the author of The application will be

identified if needed. When an application is installed in The phone is assigned a user

ID, thus avoiding it from affecting it Other applications by creating a sandbox for it.

Page 80: Chapter 5 Intent

This user ID is permanent on which devices and applications with the same user ID

are allowed to run in a single process. This is a way to ensure that a malicious

application has Can not access / compromise the data of the genuine application.

It is mandatory for an application to list all the resources it will Access during

installation. Terms are required of an application, in The installation process should

be user-based or interactive Check with the signature of the application.

The purpose of a permission is to protect the privacy of an Android user. Android

apps must request permission to access sensitive user data (such as contacts and

SMS), as well as certain system features (such as camera and internet). Depending

on the feature, the system might grant the permission automatically or might prompt

the user to approve the request.

Security program overview

The key components of the Android Security Program include:

• Design review: The Android security process begins early in the development

lifecycle with the creation of a rich and configurable security model and design. Each

major feature of the platform is reviewed by engineering and security resources, with

appropriate security controls integrated into the architecture of the system.

• Penetration testing and code review: During the development of the platform,

Android-created and open source components are subject to vigorous security

reviews. These reviews are performed by the Android Security Team, Google’s

Information Security Engineering team, and independent security consultants. The

goal of these reviews is to identify weaknesses and possible vulnerabilities well

Page 81: Chapter 5 Intent

before major releases, and to simulate the types of analysis that are performed by

external security experts upon release.

• Open source and community review: AOSP enables broad security review by any

interested party. Android also uses open source technologies that have undergone

significant external security review, such as the Linux kernel. Google Play provides

a forum for users and companies to provide information about specific apps directly

to users.

• Incident response: Even with these precautions, security issues may occur after

shipping, which is why the Android project has created a comprehensive security

response process. Full-time Android security team members monitor the Android-

specific and the general security community for discussion of potential

vulnerabilities and review security bugs filed on the Android bug database. Upon

the discovery of legitimate issues, the Android team has a response process that

enables the rapid mitigation of vulnerabilities to ensure that potential risk to all

Android users is minimized

• Monthly security updates: The Android security team provides monthly updates to

Google Android devices and all our device manufacturing partners.

Page 82: Chapter 5 Intent

API Keys

New Users: Before you can start using the Google Maps Platform APIs and SDKs,

you must sign up and create a billing account. To use the Places API you must

have an API key. The API key is a unique identifier that is used to authenticate

requests associated with your project for usage and billing purposes.

Get the API key

You must have at least one API key associated with your project.

To get an API key:

1. Go to the Google Cloud Platform Console.

2. Click the project drop-down and select or create the project for which you want to add an API

key.

3. Click the menu button and select APIs & Services > Credentials.

4. On the Credentials page, click Create credentials > API key.

The API key created dialog displays your newly created API key.

5. Click Close.

The new API key is listed on the Credentials page under API keys.

(Remember to restrict the API key before using it in production.)

Page 83: Chapter 5 Intent

Publish Your App

Publishing is the general process that makes your Android applications available to

users. When you publish an Android application you perform two main tasks:

• You prepare the application for release.

During the preparation step you build a release version of your application, which

users can download and install on their Android-powered devices.

• You release the application to users.

During the release step you publicize, sell, and distribute the release version of your

application to users.

Documenting the process of publishing an app on the Google Play Store as I go

through it for the first time.

Step 1: Sign up

Sign up for an account on the Android Developer Console. Creating an account costs

$25.

Step 2: Create a new application

• On the Developer Console select the Publish an Android Application option.

• Fill out the details: Title, Short Description, Full Description.

Page 84: Chapter 5 Intent

Step 3: Prepare multimedia

• Screenshots: I used the android emulator to take screenshots of my app.

• Hi-res icon: I used the launcher icon. It was an SVG file, so I converted it to PNG

using GIMP.

• Feature graphic: This is an image that shows up on the top of the app download

page in Google Play on mobile phones.

Step 4: Prepare code for release

• Remove log statements.

• Remove the android:debuggable attribute from your manifest file. I didn’t have

to do this because Android Studio automatically sets this attribute based on the

kind of APK its building. Neat!

• Set the android:versionCode attribute in the manifest tag in manifest.xml. Two

important notes: (1) This must be an integer that increases with each release. (2)

This number is not displayed to users.

I chose “1”.

• Set the android:versionName attribute in the manifest tag in manifest.xml. This

string is shown to users and has no other purpose.

I chose “1.0”.

Step 5: Build a release-ready APK

The release-ready APK is different from the debug APK in that it is signed with

certificate that is owned by the developer. This is done to ensure that updates to the

app come from a verified source, i.e. a developer with access to the private key.

I recommend you follow the instructions here to create a signed APK.

TL;DR? Here are some important take-away points:

• Android Studio -> Build -> Generate Signed APK

• A Java Keystore (JKS) is a repository of public-private key pairs.

Page 85: Chapter 5 Intent

• You must sign all APKs with the same key pair.

• Losing a key-pair consequences that you will not be able to push updates to your

app.

Step 6: Upload APK

Go back to the Developer Console and click on Manage Releases. Then create

a Production Release and upload your signed APK.

Google will perform a check on the APK. My app was using an SVG for the launcher

icon, which is no-bueno. I had to change it to PNG and recreate the signed APK.

Step 7:

Complete the checklist on the left until all the items have a green checkmark. The

console re-evaluates the checklist every time you click Save Draft in the top right.

You are now ready to publish :)