Download as pdf or txt
Download as pdf or txt
You are on page 1of 72

Chapter

Unit V 04

Networking and Security


Activity and Multimedia with Databases

Hours: 10 Marks: 20

Presented by:

Prof. S.S.Bhosale
Pravara Polytechnic, Loni
Specific Objective

Create Android application using


database.
5.1 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.
5.1 Intent
Intent facilitate you to redirect your activity to another
activity on occurrence of any event.
By calling, startActivity() you can perform this task.
eg.
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
startActivity(intent);

In the above example, foreground activity is getting


redirected to another activity i.e. SecondActivity.java.
getApplicationContext() returns the context for your
foreground activity.
5.1 Types of Intents:
Intent are of two types:
Explicit Intent and Implicit Intent
5.1 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
5.1 Implicit Intent:
Let’s take an example to understand Implicit Intents
more clearly.
We have to open a website using intent in your
application.
eg.

Intent intent= new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
5.1 Explicit Intent:
Explicit intent going to be connected internal world of
application, suppose if you wants to connect one
activity to another activity, we can do this quote by
explicit intent, below image is connecting first activity
to second activity by clicking button.
5.1 Explicit Intent:
Explicit Intents are used to connect the application
internally.
In Explicit we use the name of component which will be
affected by Intent.
For Example: If we know class name then we can
navigate the app from One Activity to another activity
using Intent.
In the similar way we can start a service to download a
file in background process.
5.1 Explicit Intent:
Explicit Intent work internally within an application to
perform navigation and data transfer.

eg.

Intent intent = new Intent(getApplicationContext(),


SecondActivity.class);
startActivity(intent);
5.1 intent filter
- An intent filter is an instance of the intent filter class.

- Intent filters are helpful while using implicit intents, It


is not going to handle in java code, we have to set it up
in AndroidManifest.xml.

- Android must know what kind of intent it is launching


so intent filters give the information to android about
intent and actions.

- Before launching intent, android going to do <action>


, <category> and <data> .
5.1 intent filter

Elements In Intent Filter:

There are following three elements in an intent filter:

1. action
2. data
3. category
5.1 intent filter
1. action:

It represent an activities action, what an activity is going


to do. It is declared with the name attribute as given
below
<action android:name = "string" />

An Intent Filter element must contain one or more


action element. Action is a string that specifies the
action to perform.
5.1 intent filter

You can declare your own action as given below.


But we usually use action constants defined by Intent
class.

Intent intent= new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("https://www.facebook.com"));
startActivity(intent);
5.1 intent filter
2. Data:
There are two forms in which you can pass the data,
using URI(Uniform Resource Identifiers) or MIME type
of data.

The syntax of data attribute is as follows:

<data android:scheme="string" android:host="string"


android:port="string" android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
5.1 intent filter
3. Category:
This attribute of Intent filter dictates the behavior or
nature of an Intent. There is a string which contains
some additional information about the intent which will
be handled by a component. The syntax of category is
as follows:

<category android:name="string" />


Most of Intents do not require a category for example:

CATEGORY_BROWSABLE,
CATEGORY_LAUNCHER.
5.1 intent filter
BROWSABLE – Browsable category, activity allows itself to
be opened with web browser to open the reference link provided
in data.

LAUNCHER – Launcher category puts an activity on the top of


stack, whenever application will start, the activity containing this
category will be opened first.

<intent-filter> <!--Code here-->


<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter> <!--Code here--> <category
android:name="android.intent.category.BROWSABLE" />
</intent-filter>
5.1 intent filter
ACTION DATA MEANING
Opens phone application and
Intent.ACTION_CALL tel:phone_number
calls phone number
Opens phone application and
Intent.ACTION_DIAL tel:phone_number dials (but doesn’t call)
phone_number
Opens phone application and
Intent.ACTION_DIAL voicemail: dials (but doesn’t call) the voice
mail number.
Opens the maps Application
Intent.ACTION_VIEW geo:lat,long
centered on (lat, long).
Opens the maps application
Intent.ACTION_VIEW geo:0,0?q=address centered on the specified
address.

http://url Opens the browser application


Intent.ACTION_VIEW
https://url to the specified address.

Opens the browser application


Intent.ACTION_WEB_SEARCH plain_text and uses Google search for
given string
5.2 Activity Lifecycle
5.3 Broadcast Receivers
5.3 Broadcast Receivers

Broadcast Receivers simply respond to broadcast


messages from other applications or from the system
itself.

These messages are sometime called events or intents.

For example, applications can also initiate broadcasts to


let other applications know that some data has been
downloaded to the device and is available for them to
use, so this is broadcast receiver who will intercept this
communication and will initiate appropriate action.
5.3 Broadcast Receivers

There are following two important steps to make


BroadcastReceiver works for the system broadcasted
intents –

1. Creating the Broadcast Receiver.


2. Registering Broadcast Receiver
5.3 Broadcast Receivers
1. 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.

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show();
}}
5.3 Broadcast Receivers

2. Registering Broadcast Receiver

An application listens for specific broadcast intents by


registering a broadcast receiver
in AndroidManifest.xml file.
Consider we are going to register MyReceiver for
system generated event

ACTION_BOOT_COMPLETED which is fired by the


system once the Android system has completed the boot
process.
5.3 Broadcast Receivers

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<receiver android:name="MyReceiver">
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED">
</action>
</intent-filter>
</receiver>
</application>
5.3 Broadcast Receivers
Sr.No Event Constant & Description
android.intent.action.BATTERY_CHANGED
1 Sticky broadcast containing the charging state, level, and other information about the battery.
android.intent.action.BATTERY_LOW
2 Indicates low battery condition on the device.

android.intent.action.BATTERY_OKAY
3 Indicates the battery is now okay after being low.

android.intent.action.BOOT_COMPLETED
4 This is broadcast once, after the system has finished booting.

android.intent.action.BUG_REPORT
5
Show activity for reporting a bug.
android.intent.action.CALL
6
Perform a call to someone specified by the data.
android.intent.action.CALL_BUTTON
7 The user pressed the "call" button to go to the dialer or other appropriate UI for placing a call.
android.intent.action.DATE_CHANGED
8
The date has changed.
5.4 Content provider

- A content provider component supplies data from one


application to others on request.

- Such requests are handled by the methods of the


ContentResolver class.

- A content provider can use different ways to store its


data and the data can be stored in a database, in files,
or even over a network.
5.4 Content provider
5.4 Content provider

Sometimes it is required to share data across applications.


This is where content providers become very useful.
5.4 Content provider

- Content providers let you centralize content in one place


and have many different applications access it as needed.
- A content provider behaves very much like a database
where you can query it, edit its content, as well as add or
delete content using insert(), update(), delete(), and query()
methods.
- In most cases this data is stored in an SQlite database.

A content provider is implemented as a subclass


of ContentProvider class and must implement a standard
set of APIs that enable other applications to perform
transactions.
public class My Application extends ContentProvider { }
5.5 Fragment

-A Fragment is a piece of an activity which enable


more modular activity design.
-A fragment is a kind of sub-activity.

Following are important points about fragment :


- A fragment has its own layout and its own behavior
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.
5.5 Fragment

- A fragment can be used in multiple activities.


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.
- A fragment can implement a behavior that has
no user interface component.
- Fragments were added to the Android API in
Honeycomb version of Android which API
version 11.
5.5 Fragment
how two UI modules defined by fragments can be combined into
one activity for a tablet design, but separated for a handset
design.
5.4 Fragment Life Cycle
5.4 Types of Fragments

Basically fragments are divided as three stages as shown below.

1. Single frame fragments:


Single frame fragments are using for hand hold devices like
mobiles, here we can show only one fragment as a view.

2. List fragments:
fragments having special list view is called as list fragment

3. Fragments transaction:
Using with fragment transaction. we can move one fragment to
another fragment.
5.5 Services
A service is a component that runs in the background
to perform long-running operations without needing to
interact with the user and it works even if application
is destroyed.
A service can essentially take two states :

1. 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.
5.5 Services

2. 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).
5.5 Services
5.5.1 Permissions

App permissions help support user privacy by


protecting access to the following:

Restricted data, such as system state and a user's


contact information.
Restricted actions, such as connecting to a paired
device and recording audio.

Android categorizes permissions into different types,


including install-time permissions, runtime
permissions, and special permissions.
5.5.1 Permissions
Each permission's type indicates the scope of restricted data
that your app can access, and the scope of restricted actions that
your app can perform, when the system grants your app that
permission.
To add external storage the permission to read and write. For
that you need to add permission in android Manifest file.
Open AndroidManifest.xml file and add permissions to it just
after the package name.
eg.
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE”>
<uses-permission
android:name="android.permission.READ_EXTERNAL_STORAGE”>

<uses-permission android:name="android.permission.INTERNET“>
5.6 Android MediaPlayer class

- Android provides many ways to control playback of


audio/video files and streams.
- One of this way is through a class called MediaPlayer.
Android is providing MediaPlayer class to access built-in
mediaplayer services like playing audio,video e.t.c.
- In order to use MediaPlayer, we have to call a static
Method create() of this class.
- This method returns an instance of MediaPlayer class.
Its syntax is as follows :

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);


5.6 Android MediaPlayer class

- The second parameter is the name of the song that you


want to play.
- You have to make a new folder under your project with
name raw and place the music file into it.
-Once you have created the Mediaplayer object you can
call some methods to start or stop the music.

These methods are listed below:

mediaPlayer.start();
mediaPlayer.pause();
mediaPlayer.reset();
5.6 Android MediaPlayer class

- On call to start() method, the music will start playing


from the beginning.
- If this method is called again after the pause() method,
the music would start playing from where it is left and not
from the beginning.
- In order to start music from the beginning, you have to
call reset() method.

Its syntax is given below:

mediaPlayer.reset();
5.6 Android MediaPlayer class

Sr.No Method & description


1 isPlaying()
This method just returns true/false indicating the song is
playing or not
2 seekTo(position)
This method takes an integer, and move song to that particular
position millisecond
3 getCurrentPosition()
This method returns the current position of song in milliseconds
4 getDuration()
This method returns the total time duration of song in
milliseconds
5 reset()
This method resets the media player
5.6 Android MediaPlayer class

Sr.No Method & description


6 release()
This method releases any resource attached with
MediaPlayer object
7 setVolume(float leftVolume, float rightVolume)
This method sets the up down volume for this player
8 setDataSource(FileDescriptor fd)
This method sets the data source of audio/video file
9 selectTrack(int index)
This method takes an integer, and select the track from the
list on that particular index
10 getTrackInfo()
This method returns an array of track information
5.7 Video Player

-In Android, VideoView is used to display a video file.


- It can load images from various sources (such as content
providers or resources) taking care of computing its
measurement from the video
-You have to create a new raw folder in res directory.

VideoView code In XML Android:

<VideoView android:id="@+id/vdv1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
5.7 Video Player

VideoView v1=(VideoView)findViewById(R.id.vdv1);

// set Media Controller to enable play,pause,forword etc

MediaController media=new MediaController(this);


media.setAnchorView(v1);

//Location of media file


Uri uri=
Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.video2);
v1.setMediaController(media);
v1.setVideoURI(uri);
v1.requestFocus();
v1.start();
5.8 TexttoSpeech

- Android allows you convert your text into voice.


- Not only you can convert it but it also allows you to speak text in
variety of different languages.
- Android provides TextToSpeech class for this purpose.
- In order to use this class, you need to instantiate an object of this
class and also specify the initListener.

Its syntax is given below :

private EditText write;


ttobj=new TextToSpeech(getApplicationContext(), new
TextToSpeech.OnInitListener()
{ @Override
public void onInit(int status)
{ } });
5.8 TexttoSpeech

- Different Language can be set by calling setLanguage() method.


Its syntax is given below :

ttobj.setLanguage(Locale.UK);
- The method setLanguage takes an Locale object as parameter.
- The list of some of the locales available are given below :
Sr.No Locale
1 US
2 CANADA_FRENCH
3 GERMANY
4 ITALY
5 JAPAN
6 CHINA
5.9 Sensors
-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.

1. Motion Sensors
2. Environmental sensors
3. Position sensors

- Some of the sensors are hardware based and some are


software based sensors.
- Whatever the sensor is, android allows us to get the raw data
from these sensors and use it in our application.
5.9 Sensors

- For this android provides us with some classes.


- 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);
5.10 Camera

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);
5.10 Camera
Sr.No Intent type and description
ACTION_IMAGE_CAPTURE_SECURE
1 It returns the image captured from the camera , when the device is
secured
ACTION_VIDEO_CAPTURE
2 It calls the existing video application in android to capture video
EXTRA_SCREEN_ORIENTATION
3
It is used to set the orientation of the screen to vertical or landscape
EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA
5 This intent is used to launch the camera in the video mode
EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
5.11 Bluetooth

- Among many ways, 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
5.11 Bluetooth

-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();
5.11 Bluetooth

In order to enable the Bluetooth of your device:

Intent turnOn = new


Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);

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; pairedDevices =


BA.getBondedDevices();
5.11 Bluetooth
Sr.No Method & description
enable()
1
This method enables the adapter if not enabled
isEnabled()
2
This method returns true if adapter is enabled
disable()
3
This method disables the adapter
getName()
4
This method returns the name of the Bluetooth adapter
setName(String name)
5
This method changes the Bluetooth name
getState()
6
This method returns the current state of the Bluetooth Adapter.
startDiscovery()
7 This method starts the discovery process of the Bluetooth for 120 seconds.
5.12 Animation

- Animation is the process of creating motion and shape


change

Tween Animation:
- Tween Animation takes some parameters such as start
value , end value, size , time duration , rotation angle etc.
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.
5.12 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);
5.12 Animation

- This animation class has many useful functions which are


listed below :
- 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);


image1.startAnimation(animation);
5.12 Animation

Sr.No Method & Description


start()
1
This method starts the animation.
setDuration(long duration)
2 This method sets the duration of an animation.

getDuration()
3 This method gets the duration which is set by above method

end()
4
This method ends the animation.
cancel()
5 This method cancels the animation.
5.13 SQLite Database

SQLite is a Structure query base database, open source,


light weight, no network access and standalone database.
It support embedded relational database features.
5.13 SQLite Database

SQLite is an open-source relational database i.e. used to


perform database operations on android devices such as
storing, manipulating or retrieving persistent data from the
database.

It is embedded in android by default. So, there is no need to


perform any database setup or administration task.

SQLiteOpenHelper class provides the functionality to use


the SQLite database.
5.13 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
etc.
Database – Package

The main package is android.database.sqlite that contains


the classes to manage your own databases
5.13 SQLite Database

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);
5.13 SQLite Database
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()
5.13 SQLite Database

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


poly(Username VARCHAR,Password VARCHAR);");
mydatabase.execSQL("INSERT INTO poly
VALUES('admin','admin');");
5.13 SQLite Database

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
5.13 SQLite Database
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
5.13.1 Database Helper class

Database - Helper class

For managing all the operations related to the database , an


helper class has been given and is called.
eg.

SQLiteOpenHelper openHelper=new
databaseHelper(this);

To Write data into database:

SQLiteDatabase db=openHelper.getWritableDatabase();
5.13.1 Database Helper class
Its syntax is given below:
public class databaseHelper extends SQLiteOpenHelper
{
public databaseHelper(@Nullable Context context) {
}
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " +TABLE_NAME+ "(ID INTEGER
PRIMARY KEY AUTOINCREMENT,name TEXT,address
TEXT,phone TEXT,email TEXT)");
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
Socket
Thank You
 Network socket is an endpoint of an inter-
process communication flow across a
computer network.

 Sockets provide the communication


mechanism between two computers using
TCP/IP.

You might also like