0% found this document useful (0 votes)
51 views56 pages

Unit-5 Notes - 250307 - 230640

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views56 pages

Unit-5 Notes - 250307 - 230640

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Unit-V Activity and Multimedia with Databases

Marks-20

Course Outcome:
Create Android application using database.

Unit Outcomes:
5a. Apply the given Intents and service in Application development.
5b. Use Fragment to generate the given multiple activities.
5c. Develop programs to play the given multimedia.
5d. Write the query to perform the given database management operation.

Contents:
5.1 Intent, Intent Filter
5.2 Activity Lifecycle; Broadcast lifecycle
5.3 Content Provider; Fragments
5.4 Service: Features Of service, the Android platform service, defining new service, Service
Lifecycle, Permission, example of service
5.5 Android System Architecture, Multimedia framework, Play Audio and Video, Text to speech,
Sensors, Async tasks
5.6 Audio Capture, Camera
5.7 Bluetooth, Animation
5.8 SQLite Database, necessity of SQLite, Creation and connection of the database, extracting value
from cursors, Transactions.

5.1 Intent-
 What is intent?
- Android uses Intent for communicating between the components of an Application and
also from one application to another application.
- Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc.
- Example: Intent facilitate you to redirect your activity to another activity on occurrence of
any event.
- By calling, startActivity() you can perform this task.

Example to create Intent :-


Intent obj = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(obj);

In the above example,


- getApplicationContext() returns the context for your foreground activity.
- foreground activity is getting redirected to another activity i.e. SecondActivity.java.

Intents are the objects of android.content.Intent types.

An Intent can be used to:


1. Start an activity
2. Start a service
3. Deliver a broadcast

Intents are mainly useful to perform the following,


Component Description
- startActivity() method is used.
Starting an
Activity By sending an Intent object to startActivity() method we can start a new Activity
or existing Activity to perform required things.
- startService() method is used.
Starting a
Service By sending an Intent object to startService() method we can start a new Service
or send required instructions to an existing Service.
- sendBroadcast() method is used.
Delivering a
Broadcast By sending an Intent object to sendBroadcast() method we can deliver or send
our messages to other app broadcast receivers.

 In android, Activity represents a single screen with a user interface (UI) of an application
and it will acts an entry point for users to interact with an app.
 In android, Service is a component which keep an app running in the background to
perform long-running operations based on our requirements. For Service, we don’t have
any user interface and it will run the apps in the background like playing the music in the
background or handle network operations when the user in a different app.
 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.
 Types of Intents:
Intent are of two types: Explicit Intent and Implicit Intent

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.
 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.
 Explicit Intent work internally within an application to perform navigation and data
transfer. The below given code snippet will help you understand the concept of Explicit
Intents.

Example:-
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(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.
 Let’s take an example to understand Implicit Intents more clearly. We have to open a website
using intent in your application. See the code snippet given below.
 Example-
Intent intentObj = new Intent(Intent.ACTION_VIEW);
intentObj.setData(Uri.parse("https://www.google.com"));
startActivity(intentObj);

Example of Intent
Step 1: Design the UI of first activity activity_main.xml (it contains 2 buttons. 1st button to
execute explicit intent and 2nd button to execute implicit intent.)

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation=”Vertical”>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Explicit Intent Example"
android:id="@+id/explicit_Intent"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Implicit Intent Example"
android:id="@+id/implicit_Intent"/>

</LinearLayout>

Step 2: Design the UI of second activity activity_second.xml


activity_second.xml (Go to layout folder, create a new activity and name it activity_second.xml)

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


<LinearLayout 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:orientation="horizontal">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is Second Activity"/>

</LinearLayout>

Step 3: Implement onClick event for Implicit and Explicit Button inside MainActivity.java

MainActivity.java
package com.example.android.intents;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity


{

Button ebtn, ibtn;


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

ebtn = (Button)findViewById(R.id.explicit_Intent);
ibtn = (Button)findViewById(R.id.implicit_Intent);

//implement Onclick event for Explicit Intent


ebtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(getBaseContext(),
SecondActivity.class);
startActivity(intent);
}
});

//implement onClick event for Implicit Intent


ibtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
}
});

}
}

Step 4: Create A New JAVA class name SecondActivity

SecondActivity.java
package com.example.android.intents;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class SecondActivity extends AppCompatActivity


{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);

Toast.makeText(getApplicationContext(), "We moved to second


Activity",Toast.LENGTH_LONG).show();
}
}

Step 5: Manifest file:


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.intents" >

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >

<activity android:name=".MainActivity" >


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

<activity android:name=".SecondActivity" >


</activity>
</application>
</manifest>

5.1 Intent Filter in Android Manifest :-


 Intent Filter are the components which decide the behavior of an intent.
 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.
 It declares the functionality of its parent component (i.e. activity, services or broadcast
receiver).
 It declares the capability of any activity or services or a broadcast receiver.
 Intent Filter code inside Android Manifest: The code of Intent Filter is used inside
AndroidManifest.xml file for an activity.
 You can see it: open manifests folder >> open AndroidManifest.xml file
 Syntax of Intent Filters:
<intent-filter android:icon="drawable resource"
android:priority="integer"
android:label="string resource" >
...
</intent-filter>

<intent-filter attributes…….>
<elements ……..>
</intent-filter>
Attributes:-
1. android:icon
 An icon represents the activity, service or broadcast receiver when a user interact with it.
 To set an icon you need to give reference of drawable resource as:-
android:icon=“@drawable/icon”
 How to add custom icon in your App:
Step 1: Open your android project folder in computer / system
Step 2: Open app>> src >> main >> res >> drawable >> here save custom icon image with
name
Step 3: Replace @drawable/icon with @drawable/your_image name in the below code
android:icon="@drawable/icon"
 If you have not declared any icon for your activity then android sets the icon of parent
component by default.
 And if no icon is defined by parent component then icon is set as the default icon by
<application> element (declared in Manifest file).

2. android:label
 A label represents the title of an activity on the toolbar.
 You can have different Labels for different Activities as per your requirement or choice.
 The label should be set as a reference to a string resource.
 However, you can also use a raw string to set a label as declared in the below given code
snippet

android:label = "@string/label"
or
android:label = "New Activity"

 How To Create Custom Label in App:


Step 1: Click on values (res/values)
Step 2: Open Strings.xml file present inside values
Step 3: Edit String value to your custom name.

 If you have not declared any label for your activity then it will be same as your parent
activity.
 However if you haven’t declared any label to parent activity then label is set by
<application> element’ label attribute.

3)android:priority
 The priority given to the parent component with regard to handling intents of the type
described by the filter.
 This attribute has meaning for both activities and broadcast receivers.
 It provides information about how an activity is to respond to an intent that matches the filter,
relative to other activities that can also respond to the intent.
 When an intent can be handled by multiple activities with different priorities, Android
considers only those with higher priority values as potential targets for the intent.
 It controls the order in which broadcast receivers are executed to receive broadcast
messages, with those having higher priority values being called before those having lower
values.
 The value is an integer, such as 100. Higher numbers have a higher priority. The default value
is 0
 A non-privileged application requests any priority >0.
 A privileged application requests a priority >0 for ACTION_VIEW, ACTION_SEND,
ACTION_SENDTO or ACTION_SEND_MULTIPLE.

Elements in Intent Filter:


There are following three elements in an intent filter:
1. Action
2. Data
3. Category

Important Note: Every intent filter must contain action element in it. Data and category
elements are optional for it.

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.
 You can declare your own action as given below.
 But we usually use action constants defined by Intent class.

<intent-filter>
<action android:name="com.example.android.intentfilters.Main2Activity"/>
</intent-filter>

There are few common actions for starting an activity like ACTION_VIEW

ACTION_VIEW: This is used in an Intent with startActivity(). This helps when you redirect to see
any website, photos in gallery app or an address to view in a map app.

For example: As we have done in previous example, we started a website using implicit intent in that
Intent we used ACTION_VIEW element to view website in the web browser.

Intent intentObj = new Intent(Intent.ACTION_VIEW);


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

There are more actions similar to above like, ACTION_SEND, ACTION_MAIN,


ACTION_WEB_SEARCH and many more.

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" />

This specifies the format of data associated with an Intent which you use with component. As
explained in above code snippet, data passed through Intent is a type of URI. Check the below
given table for better clarification

ACTION DATA MEANING


Intent.ACTION_CALL tel:phone_number Opens phone application and calls phone
number
Intent.ACTION_DIAL tel:phone_number Opens phone application and dials (but
doesn’t call) phone_number
Intent.ACTION_DIAL voicemail: Opens phone application and dials (but
doesn’t call) the voice mail number.
Intent.ACTION_VIEW geo:lat,long Opens the maps Application centered on (lat,
long).
Intent.ACTION_VIEW http://url Opens the browser application to the specified
https://url address.
Intent.ACTION_WEB_SEARCH plain_text Opens the browser application and uses
Google search for given string

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.

Example of category : CATEGORY_BROWSABLE, CATEGORY_LAUNCHER.

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.2 Activity Lifecycle -


 Activity is one of the building blocks of Android OS.
 In simple words 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.
 In other words we can say Activity is a class pre-written in Java Programming.
 Activities in the system are managed as an activity stack.
 When a activity is happening, it is placed on the top of the stack and become the running
activity.
Hint- 1-3-1-3-1
L-CSR-R-PSD-S
C-P-S S-R-S

Method Description
onCreate() called when activity is first created.
onStart() called when activity is becoming visible to the user.
onResume() called when activity will start interacting with the user.
onPause() called when activity is not visible to the user.
onStop() called when activity is no longer visible to the user.
onRestart() called after your activity is stopped, prior to start.
onDestroy() called before the activity is destroyed.

The onCreate() and onDestroy() methods are called only once throughout the activity lifecycle.
The Activity lifecycle consists of 7 methods:
 onCreate() : It is called when an activity is first created. When a user opens the app then some
Activity is created. You have to implement this method in every activity because, inside this
method, all the necessary components of your activity will be initialized. Here the initialization
of your application's UI is done.
 onStart(): This method is called when an activity becomes visible to the user. When all the
initialization is done by the onCreate() method, then this method is called.
 onResume(): It is called just before the user starts interacting with the application. Most of the
core functionalities of the app are implemented in this method.
 onPause(): It is called when the activity is paused i.e. it is mostly called when you press the
back or home button of your Android device. It is an indication that the user is leaving the
activity and starting some other activity.
 onStop(): It is called when the activity is no longer visible to the user. If you are starting a new
activity, or some existing activity is entering into
 onResume() state, then the current activity will not be visible to the user and is stopped.
 onRestart(): It is called when the activity in the stopped state is about to start again. By doing
so, the state of the activity from the time it was stopped will be restored.
 onDestroy(): It is called when the activity is totally destroyed i.e. when you clear the
application stack then onDestroy() will be called and all the states of the activity will be
destroyed

Example

package com.example.activitylifecycledemo;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart()
{
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume()
{
super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause()
{
super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop()
{
super.onStop();
Log.d("lifecycle","onStop invoked");
}
@Override
protected void onRestart()
{
super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy()
{
super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}

You will not see any output on the emulator or device. You need to open logcat.
Now click on the HOME Button. You will see onPause method is invoked.

After a while, you will see onStop method is invoked.

5.2 Android BroadcastReceivers


 Broadcast Receiver is a component that will allow an android system or other apps to deliver
events to the app like sending a low battery message or screen turned off the 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 Intents are used to deliver broadcast events to other apps and Broadcast Receivers
use status bar notifications to let the user know that broadcast event occurs.
 In android, Broadcast Receiver is implemented as a subclass of BroadcastReceiver and each
broadcast is delivered as an Intent object.
1. Receiving Broadcasts
 In android, we can receive broadcasts by registering in two ways.
a. One way is by registering broadcasts using an android application manifest file
(AndroidManifest.xml).
- Need to specify <receiver> element in apps manifest file like as shown below.
Syntax:
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
- The above statement will fire the defined system broadcast event whenever the boot
process is completed.
b. Another way is to register a receiver dynamically using Context.registerReceiver()
method.
 To register broadcast receiver we need to extend our class using BroadcastReceiver
and need to implement an onReceive(Context, Intent) method like as shown below.
Syntax:
public class MainActivity extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, log, Toast.LENGTH_LONG).show();
}
}
 Suppose if we register for ACTION_BOOT_COMPLETED event, whenever the boot
process is completed the broadcast receiver’s method onReceive() method will be
invoked.
2. Sending Broadcasts
 In android, we can send a broadcasts in apps using three different ways, those are

Method Description
This method is used to send broadcasts to one receiver
sendOrderedBroadcast(Intent, String)
at a time.
This method is used to send broadcasts to all receivers
sendBroadcast(Intent)
in an undefined order.
This method is used to send broadcasts to receivers that
LoadBroadcastManager.sendBroadcast
are in the same app as the sender.

Broadcasting Custom Intents


Simple code snippet of sending a broadcast by creating an intent using sendBroadcast(Intent)
method.
Intent sintent = new Intent();
sintent.setAction("com.tutlane.broadcast.MY_NOTIFICATION");
sintent.putExtra("data","Welcome to Tutlane");
sendBroadcast(sintent);
Register our intent action in android manifest file like as shown below
<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name=" com.tutlane.broadcast.MY_NOTIFICATION"/>
</intent-filter>
</receiver>
This is how we can create our own custom broadcasts using Intents in android applications.

System Broadcasts
 System events are defined as final static fields in the Intent class.
 The following are some of the system events available in android applications.

Event Description
android.intent.action.BOOT_COMPLETED It raises an event, once boot completed.
It is used to trigger an event when power connected
android.intent.action.POWER_CONNECTED
to the device.
It is used to trigger an event when the power got
android.intent.action.POWER_DISCONNECTED
disconnected from the device.
It is used to call an event when battery is low on
android.intent.action.BATTERY_LOW
device.
It is used to call an event when a battery is OKAY
android.intent.action.BATTERY_OKAY
again.
android.intent.action.REBOOT It call an event when the device rebooted again.

5.3 Fragment
 Android Fragment is the part of activity, it is also known as sub-activity.
 There can be more than one fragment in an activity.
 Fragments represent multiple screen inside one activity.
 Android fragment lifecycle is affected by activity lifecycle because fragments are
included/embedded in activity.
 The FragmentManager class is responsible to make interaction between fragment objects.
 There are 12 lifecycle methods for fragment.
 Android Fragment Lifecycle Methods
No. Method Description
1) onAttach(Activity) it is called only once when it is attached with activity.
2) onCreate(Bundle) It is used to initialize the fragment.
onCreateView(LayoutInflater,
3) creates and returns view hierarchy.
ViewGroup, Bundle)
4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.
It provides information to the fragment that all the saved
5) onViewStateRestored(Bundle)
state of fragment view hierarchy has been restored.
6) onStart() makes the fragment visible.
7) onResume() makes the fragment interactive.
8) onPause() is called when fragment is no longer interactive.
9) onStop() is called when fragment is no longer visible.
10) onDestroyView() allows the fragment to clean up resources.
allows the fragment to do final clean up of fragment
11) onDestroy()
state.
It is called immediately prior to the fragment no longer
12) onDetach()
being associated with its activity.

Android Fragment Example


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context="example.javatpoint.com.fragmentexample.MainActivity">

<fragment
android:id="@+id/fragment1"
android:name="example.javatpoint.com.fragmentexample.Fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />

<fragment
android:id="@+id/fragment2"
android:name="example.javatpoint.com.fragmentexample.Fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1" />

</LinearLayout>

fragment_fragment1.xml
<FrameLayout 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"
tools:context="com.example.fragmentexample.Fragment1">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is First Fragment" />

</FrameLayout>

fragment_fragment2.xml
<FrameLayout 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"
tools:context="com.example.fragmentexample.Fragment2">

<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="This is Second Fragment" />
</FrameLayout>

MainActivity.java
package com.example.fragmentexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Fragment1.java
package com.example.fragmentexample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}

Fragment2.java
package com.example.fragmentexample;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}

5.3 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.
 In android, Content Provider will act as a central repository to store the data of the
application in one place and make that data available for different applications to access
whenever it’s required.
 In android, we can configure Content Providers to allow other applications securely access
and modify our app data based on our requirements.
 Generally, the Content Provider is a part of an android application and it will act like a
relational database to store the app data.
 We can perform multiple operations like insert, update, delete and edit on the data stored
in content provider using insert(), update(), delete() and query() methods.
 In android, we can use content provider whenever we want to share our app data with
other apps and it allow us to make a modifications to our application data without
effecting other applications which depends on our app.
 By using content providers we can manage data such as audio, video, images and personal
contact information.
 We have different type of access permissions available in content provider to share the
data.
 We can set a restrict access permissions in content provider to restrict data access limited
to only our application and we can configure different permissions to read or write a
data.
 Sometimes it is required to share data across applications. This is where content providers
become very useful.
 Content providers let you centralize content in one place and have many different
applications access it as needed.
 In most cases this data is stored in a 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.
Syntax:

public class MyApplication extends ContentProvider {


}

Create Content Provider


1. First of all you need to create a Content Provider class that extends the ContentProvider
baseclass.
2. Second, you need to define your content provider URI address which will be used 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. register content provider in AndroidManifest.xml using <provider> tag.

List of methods which you need to override in Content Provider class to have your Content
Provider working –
onCreate() - This method will initialize our provider. The android system will call this method
immediately after it creates our provider.
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.
insert() - This method will insert a new row into our content provider and it will return the content
URI for newly inserted row.
delete() - This method will delete the rows in our content provider and it return the number of rows
deleted.
update() - This method will update an existing rows in our content provider and it return the number
of rows updated.
getType() - This method will return the MIME type of data to given content URI.

Content URIs
- In android,Content URI is an URI which is used to query a content provider to get the required
data. The Content URIs will contain the name of entire provider (authority) and the name that
points to a table (path).

General format of URI


- content://authority/path
- Following are the details about various parts of an URI in android application.
- content:// -The string content:// is always present in the URI and it is used to represent the
given URI is a content URI.
- authority-It represents the name of content provider, for example phone, contacts, etc. and we
need to use fully qualified name for third party content providers like
com.examples.contentprovider
- path- It represents the table’s path.

5.4 Android Service


 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 have any UI (user interface).
 The service runs in the background indefinitely even if application is destroyed.
 Moreover, service can be bounded by a component to perform interactivity and
inter process communication (IPC).
 Types of Android Services-
1. Foreground Services:
- Services that notify the user about its ongoing operations are termed as
Foreground Services.
- Users can interact with the service by the notifications provided about the
ongoing task.
- Such as in downloading a file, the user can keep track of the progress in
downloading and can also pause and resume the process.

2. Background Services:
- Background services do not require any user intervention.
- These services do not notify the user about ongoing background tasks and
users also cannot access them.
- The process like schedule syncing of data or storing of data fall under this service.

3. Bound Services:
- This type of android service allows the components of the application like
activity to bound themselves with it.
- Bound services perform their task as long as any application component is
bound to it.
- More than one component is allowed to bind themselves with a service at a time.
- In order to bind an application component with a service bindService() method is
used.

Life Cycle of Android Service-


 There can be two forms of a service.
 The lifecycle of service can follow two different paths: started or bound.
1) Started Service - A service is started when component (like activity) calls
startService() method. Once initiated can run in the background indefinitely. It is
stopped by stopService() method. The service can stop itself by calling the
stopSelf() method.
2) Bound Service - A service is bound when another component (e.g. client) calls
bindService() method. The client can unbind the service by calling the
unbindService() method. The service cannot be stopped until all clients unbind the
service.
 onCreate() - This is the first callback which will be invoked when any component
starts the service. If the same service is called again while it is still running this
method won’t be invoked.
 onStartCommand() - This callback is invoked when service is started by any
component by calling startService(). It basically indicates that the service has
started and can now run indefinetly.
 onBind() - This is invoked when any component starts the service by calling
onBind.
 onUnbind() - This is invoked when all the clients are disconnected from the
service.
 onRebind() - This is invoked when new clients are connected to the service. It is
called after onUnbind.
 onDestroy() - This is a final clean up call from the system. This is invoked just
before the service is being destroyed. It’s very useful to cleanup any resources such
as threads, registered listeners, or receivers.

5.4 Android Multimedia Framework


 The android multimedia system includes multimedia applications, multimedia framework, OpenCore
engine and hardware abstract for audio/video input/output devices.
 And the goal of the android multimedia framework is to provide a consistent interface for Java
services.
 The multimedia framework consists of several core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on.
 A general multimedia framework architecture is shown in Figure
 The Media Server creates the corresponding media service to the multimedia application.
 The communication between the media server and Libmedia forms a client-server model.
 The PV player processes the media data stream by demuxing the media data to separate the
video/audio data stream, decode video/audio data, sync video, and audio time, and send the decoded
data out.
 The Android Multimedia framework is a set of APIs for developers which enables them to create a
multimedia application on an android platform.
 This framework provides support for audio, video, and images, which provides a range of features
such as media playback, recording, editing, streaming, etc.
 Components of Android Multimedia Framework
1. Media Codec -
 It provides low-level access to hardware and software codecs for encoding and decoding
audio and video data.
 Format of media codec supported by the android platform-
 Container: It is used to store audio file format on a system, where data can be manipulated to
reduce the size or change the quality of audio.
 Audio Format: Any format or codec can be used including the ones provided by android
devices. However, it is recommended to use the specified file formats as per devices.
 Network Protocol: Protocols supported in audio and video playback are RTSP, HTTP/HTTPS
progressive streaming, and live streaming draft protocol.
 Common media codec formats used in android multimedia applications include:
 H.264: Widely used video codec format that provides high-quality compression and is
supported by most modern devices and software.
 AAC: Popular audio codec format that provides high-quality compression and is widely
supported by devices and software.
 MP3: Well-known audio codec format that provides good compression and is supported
by most devices and software.
 VP9: Video codec format that provides high-quality compression and is supported by
some modern devices and software.
 JPEG: Image codec format that provides good compression and is widely supported by
devices and software.
 PNG: Image codec format That provides lossless compression which is supported by
devices and software.
2. Media Player
 It is a component in the multimedia framework that provides high-level access to the media
playback functionality of Android that enables developers to play audio/video files and
stream.
 It is also a core component of the Android multimedia framework that enables developers to
play audio and video files in their applications and provides a simple and flexible API for
playing media files from different sources.
 The sources are local files, network streams, and content providers.
 Media player supports a wide range of audio and video formats which includes MP3, AAC,
WAV, MPEG-4, H.264, etc.
 Some key features of media players are:
 Playback control: This helps in controlling media files by providing a range of methods
such as start(), pause(), stop(), and seekTo().
 Playback State: This feature informs the developer about the playback state by providing
functions that are onPrepared(), onCompletion(), and onError().
 Audio Focus: This feature comes into the picture when multiple audio sources are
playing simultaneously and the developer has to manage all of it.
 Media Streaming: The media player supports streaming media from various sources such
as HTTP, RTSP, and RTP so to handle the streaming media developers use
setDataSourse() method to set the source for streaming media and use the prepareAsync()
method to prepare the media player for asynchronous playback.
 Media Playback with the surface: To set the surface on which the video should be
rendered setSurface() is used.
3. Media Recorder
 Provides high-level access to the media recording functionality of Android which allows
developers to capture audio/video data from a device’s microphone and camera.
 It provides a simple and flexible API for recording media from different sources such as the
device’s microphone or camera.
 Features of the media recorder are:
 Recording control: This feature provides methods like start(), stop(), and reset() for
controlling the recording of media files.
 Recording state: This feature enables the user to notify about the state of recording by
using methods onInfo() and onError().
 Audio and Video Sources: This feature provides two methods setAudioSource and
setVideoSource() which enable developers to select appropriate audio and video sources
for their recordings.
 Audio and Video Encoding: For video formatting, this feature contains methods such as
setOutputFormat() method. setAudioEncoder() and setVideoEncoder() methods are used
to select appropriate encoding for audio and video.
4. Surface View
 The surface provides a facility to play video content on android devices.
 It is a subclass of the view class and provides a dedicated drawing surface for applications
that need to display video or graphics which are more complicated than simple views.
 Feature of Surface View:
 Drawing surface: This feature is used by developers to draw complex graphics or display
video frames.
 Efficient rendering: This is used when developers when designing efficient rendering is
needed and provides better performance compared to other View classes when rendering
large images or video frames.
 Compatibility with Android Graphics Framework: It is compatible with OpenGL ES,
which is a 3D graphics library that can be used to create advanced multimedia
applications.
5. Audio Manager
 Controls the overall audio settings such as volume and routing.
 It allows developers to manage audio settings and control audio playback for various
applications and devices.
 Functions of Audio Manager:
 Controlling Audio Volume
 Managing Audio Routing
 Handling Audio Focus
 Monitoring audio States
6. Image Reader
 Provides access to raw image data from a device’s camera or image sensors.
 It is a part of the android Camera2 API and is available in Android API level 19 and higher.
 Function that ImageReader class include:
 Capturing raw images
 Processing captured images
 Configuring capture settings
 Handling image buffers

5.5 Play Audio and VIdeo


 We can play and control the audio files in android with the help of MediaPlayer class.
 The android.media.MediaPlayer class is used to control the audio or video files.
 Android is providing MediaPlayer class to access built-in mediaplayer services like playing
audio, video etc.
 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);
 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.

Sr.No Method & description


public boolean isPlaying()
1
This method just returns true/false indicating the song is playing or not
public void seekTo(position)
2
This method takes an integer, and move song to that particular position millisecond
public int getCurrentPosition()
3
This method returns the current position of song in milliseconds
public int getDuration()
4
This method returns the total time duration of song in milliseconds
public void reset()
5
This method resets the media player
public void setVolume(float leftVolume, float rightVolume)
6
This method sets the up down volume for this player
public void setDataSource(FileDescriptor fd)
7
This method sets the data source of audio/video file
public void start()
8
it starts or resumes the playback.
public void stop()
9
it stops the playback.
public void setLooping(boolean looping)
10
sets the player for looping or non-looping.
public boolean isLooping()
11
checks if the player is looping or non-looping.

Example
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="pause" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="stop" />

</LinearLayout>

MainActivity.java
package com.example.audioplayerdemo;

import android.media.MediaPlayer;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.audioplayerdemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button start=(Button)findViewById(R.id.button1);
Button pause=(Button)findViewById(R.id.button2);
Button stop=(Button)findViewById(R.id.button3);

MediaPlayer mp=MediaPlayer.create(this,R.raw.bb3);

start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}

Android Video Player Example


 By the help of MediaController and VideoView classes, we can play the video files in
android.
 MediaController class - The android.widget.MediaController is a view that contains
media controls like play/pause, previous, next, fast-forward, rewind etc.
 VideoView class - The android.widget.VideoView class provides methods to play and
control the video player.
 The commonly used methods of VideoView class are as follows:
Method Description
public void setMediaController(MediaController
sets the media controller to the video view.
controller)

public void setVideoURI (Uri uri) sets the URI of the video file.

public void start() starts the video view.

public void stopPlayback() stops the playback.

public void pause() pauses the playback.

public void suspend() suspends the playback.


public void resume() resumes the playback.
public void seekTo(int millis) seeks to specified time in miliseconds.

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<VideoView
android:id="@+id/vdVw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="start" />

</LinearLayout>

MainActivity.java
package com.examples.videoplayerexample;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView =(VideoView)findViewById(R.id.vdVw);
//Set MediaController to enable play, pause, forward, etc options.
MediaController mediaController= new MediaController(this);
Button start=(Button)findViewById(R.id.button1);

start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mediaController.setAnchorView(videoView);
//Location of Media File.
//Starting VideoView By Setting MediaController and URI
videoView.setMediaController(mediaController);
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video1);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
}
});
}
}

5.5 Android TextToSpeech Example

 Text to Speech App converts the text written on the screen to speech.
 Text-to-speech is commonly used as an accessibility feature to help people who have trouble reading
on-screen text, but it’s also convenient for those who want to be read too.
 This feature has come out to be a very common and useful feature for users.
 Example-

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/Text"
android:hint="Enter Any Sentence" />

<Button
android:layout_width="wrap_content"
android:id="@+id/btnText"
android:layout_height="wrap_content"
android:text="Click Here"
android:layout_gravity="center"/>

</LinearLayout>

MainActivity.java

package com.example.texttospeechdemo;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.speech.tts.TextToSpeech;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.texttospeechdemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import java.util.Locale;

public class MainActivity extends AppCompatActivity


{
EditText Text;
Button btnText;
TextToSpeech textToSpeech;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Text = findViewById(R.id.Text);
btnText = findViewById(R.id.btnText);

textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener()


{
@Override
public void onInit(int i)
{
if(i!=TextToSpeech.ERROR)
{
textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});

btnText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
textToSpeech.speak(Text.getText().toString(),TextToSpeech.QUEUE_FLUSH,null);
}
});
}
}

Android - Sensors
 Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device.
 Types of Sensors
Android supports three types of sensors:
1) Motion Sensors
These are used to measure acceleration forces and rotational forces along with three axes.
2) Position Sensors
These are used to measure the physical position of device.
3) Environmental Sensors
These are used to measure the environmental changes such as temperature, humidity etc.
 Android Sensor API
Android sensor api provides many classes and interface. The important classes and interfaces of
sensor api are as follows:
1. SensorManager Class: Sensor manager is used to accessing various sensors present in the
device.
2. Sensor Class: The sensor class is used to get information about the sensor such as sensor name,
sensor type, sensor resolution, sensor type, etc.
3. SensorEvent class: This class is used to find information about the sensor.
4. SensorEventListener interface: This is used to perform some action when sensor accuracy
changes.
 Example to display list of sensors
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/sensorslist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sensors"/>
</LinearLayout>

MainActivity.java

package com.example.sensorsexample;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;

public class MainActivity extends AppCompatActivity


{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

SensorManager mgr=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
TextView txtList = (TextView)findViewById(R.id.sensorslist);
List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL);
StringBuffer s1=new StringBuffer();
for(Sensor s: sensorList)
{
s1.append(s.getName()+"\n");
}
txtList.setVisibility(View.VISIBLE);
txtList.setText(s1);
}
}

5.6 Android Camera Capture


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">

<Button
android:id="@+id/cbutton"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginStart="150dp"
android:text="Camera" />

<ImageView
android:id="@+id/cimage"
android:layout_width="350dp"
android:layout_height="450dp"
android:layout_marginStart="30dp"
android:layout_marginTop="70dp"
android:layout_marginBottom="10dp" />
</RelativeLayout>

MainActivity.java
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity


{

private static final int pic_id = 123;


Button cb;
ImageView ci;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

cb = findViewById(R.id.cbutton);
ci = findViewById(R.id.cimage);

cb.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent c=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(c);
}
});
}

// This method will help to retrieve the image


protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

if (requestCode == pic_id)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
ci.setImageBitmap(photo);
}
}
}
5.7 Android Animation
 Animation is the process of adding a motion effect to any view, image, or text.
 With the help of an animation, you can add motion or can change the shape of a specific view.
 Animation in Android is generally used to give your UI a rich look and feel.
 The animations are basically of three types as follows:
 Property Animation
 View Animation
 Drawable Animation
1. Property Animation
Property Animation is one of the robust frameworks which allows animation almost everything.
2. View Animation
View Animation can be used to add animation to a specific view to perform tweened animation on
views.
3. Drawable Animation
Drawable Animation is used if you want to animate one image over another. A simple example
of drawable animation can be seen in many apps Splash screen on apps logo animation.

Important functions for working with Animation


Methods Description

startAnimation() This method will start the animation.

clearAnimation() This method will clear the animation running on a specific view.

 To use Animations in Android, Android has provided us a class called Animation.


 To perform animation in android, we will call a static function loadAnimation () of the
class AnimationUtils.
 Its syntax of instance creation of Animation Object −
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);

Second parameter refers to our animation.xml file. It is created under res directory (res->anim-
>myanimation.xml)

The Animation class has many methods given below:


1.start(): This method will start the animation.
2.setDuration(long duration): This method sets the duration of an animation.
3.getDuration(): This method gets the duration.
4.end(): This method ends the animation.

Property Animation:
 This animation was introduced in Android 3.0 (API level 11). It allows the user to animate
anything.
 Property animations are highly customizable, you can specify the duration, the number of
repeats, the type of interpolation, and the frame rate of the animation.
 The Property Animation system is always preferred for more complex animations.
 Common properties commonly animated on views include:
Property Description
alpha Fade in or out
rotation, rotationX, rotationY Spin or flip
scaleX ,scaleY Grow or shrink
x,y,z Position
translationX, translationY, translationZ Offset from Position

Example
activity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/rose1" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade"
android:id="@+id/button1"
android:onClick="fade"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clockwise"
android:id="@+id/button2"
android:onClick="clockwise"/>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Move"
android:id="@+id/button3"
android:onClick="move"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Blink"
android:id="@+id/button4"
android:onClick="blink"/>

</LinearLayout>

MainActivity.java
package com.example.animatedemo;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.animatedemo.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity


{
ImageView image = (ImageView)findViewById(R.id.imageView);
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clockwise(View view)
{
Animation animation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.clockwise);
image.startAnimation(animation);
}
public void fade(View view)
{
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade);
image.startAnimation(animation1);
}
public void move(View view)
{
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.move);
image.startAnimation(animation1);
}
public void blink(View view)
{
Animation animation1 = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.blink);
image.startAnimation(animation1);
}
}

How to create animation xml files?

Right click res. Select Directory. Name it as anim. Right click ‘anim’ directory and select file, give
name such as clockwise.xml and copy below code.

A container that holds other animation elements (<alpha>, <scale>, <translate>, <rotate>) or
other <set> elements. Represents an AnimationSet.

clockwise.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:fromXScale="0.5"
android:toXScale="3.0"
android:fromYScale="0.5"
android:toYScale="3.0"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>

<scale xmlns:android="http://schemas.android.com/apk/res/android"
android:startOffset="5000"
android:fromXScale="3.0"
android:toXScale="0.5"
android:fromYScale="3.0"
android:toYScale="0.5"
android:duration="5000"
android:pivotX="50%"
android:pivotY="50%" >
</scale>
</set>
fade.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

<alpha
android:fromAlpha="0"
android:toAlpha="1"
android:duration="2000" >
</alpha>

<alpha
android:fromAlpha="1"
android:toAlpha="0"
android:duration="2000" >
</alpha>

</set>

blink.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite"/>
</set>

move.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" />
</set>

slide.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpolator"
android:toXScale="1.0"
android:toYScale="0.0" />
</set>

5.7 Bluetooth
 In Android devices, Bluetooth is a communication network protocol that allows devices to connect
wirelessly to exchange data with other Bluetooth devices.
 In general, we can make use of Bluetooth API to implement Bluetooth functionalities, such as
enabling or disabling Bluetooth, searching for available Bluetooth devices, connecting with the
devices, and managing the data transfer between devices within the range.
 In Android, the BluetoothAdapter class performs all Bluetooth-related activities.
 By default, and Bluetooth device is in an undiscoverable mode.
 This means that if we switch on the Bluetooth in a device, it is visible only to those paired earlier
with it. This device is invisible on devices other than the paired ones.
 To make this device visible, we switch on the Discoverable option, which makes the device global to
its vicinity.
 Android Set Bluetooth Permissions
 To use Bluetooth features in our android applications, need to add multiple permissions, such
as BLUETOOTH and ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION in our
manifest file.
Permission Description

BLUETOOTH We need this permission to perform any Bluetooth communication,


such as requesting a connection, accepting a connection, and
transferring data.

LOCATION We need this permission because the Bluetooth scans can be used to
gather the information about the location of user.

 Following is the example of defining the Bluetooth permissions in android manifest file.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
</manifest>

Android BluetoothAdapter Class


 In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our
applications.
 By using BluetoothAdapter object, we can interact with device’s Bluetooth adapter to perform
Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it will
return null.
 Following is the code snippet to initialize BluetoothAdapter class and to know whether the Bluetooth
is supported on the device or not.

BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();


if(bAdapter == null)
{
// Device won't support Bluetooth
}

 Android Enable or Disable Bluetooth


 If Bluetooth is supported but disabled, then the isEnabled() method will return false and we can
request the user to enable Bluetooth without leaving our application by
using startActivityForResult() method with ACTION_REQUEST_ENABLE intent action
parameter.
 Following is the code snippet to enable a Bluetooth by
using BluetoothAdapter parameter ACTION_REQUEST_ENABLE.

 if(!bAdapter.isEnabled())
{
Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(eintent, intVal);
}
 If you observe above code snippet, we used startActivityForResult() method
with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth.
 The second parameter intVal in startActivityForResult() method is a locally defined integer that
must be greater than 0 and the system will return this parameter back to us
during onActivityResult() implementation as a requestCode parameter.

 To know more about to TURN ON / OFF Bluetooth in android applications, check this Android
Bluetooth Turn ON / OFF with Examples.

 Android Enable Discoverability


 To make the device discoverable to other devices, we need to start the new activity by
calling startActivityForResult(intent, int) with
the ACTION_REQUEST_DISCOVERABLE intent.
 Following is the code snippet to enable the system’s discoverable mode to make sure that the device
discoverable to other devices.

 Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);


dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(dIntent);
 If you observe above code snippet, we are making sure our device discoverable to other devices
using ACTION_REQUEST_DISCOVERABLE. By default, the device becomes discoverable for
120 seconds. We can extend the device discoverable duration up to 3600 seconds (1 hour), by adding
the EXTRA_DISCOVERABLE_DURATION extra.

 To know more about device discoverability, check this Android Bluetooth Device Discoverability with
Examples.

 Android List Paired Devices


 By using the BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired
devices list.
 Following is the code snippet to get all paired devices with name and MAC address of each device.

 // Get paired devices.


Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
}
}

 If you observe above code, we are getting the Bluetooth paired devices name and mac address by
using BluetoothDevice object.
 To know more about Bluetooth pair devices, check this Android Bluetooth List Pair Devices with
Examples.
 This is how we can use Bluetooth in android applications to allow a devices to connect wirelessly to
exchange the data with other Bluetooth devices.

 Android Enable or Turn On Bluetooth


 In android, By using the startActivityForResult() method
with ACTION_REQUEST_ENABLE intent action parameter we can enable or turn on Bluetooth in
our android applications.
 Following is the code snippet to enable a Bluetooth by
using BluetoothAdapter parameter ACTION_REQUEST_ENABLE.

 Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);


startActivityForResult(eintent, intVal);

 If you observe above code snippet, we used startActivityForResult() method


with ACTION_REQUEST_ENABLE intent action parameter to enable a Bluetooth. The second
parameter intVal is a locally defined integer that must be greater than 0.

 Android Disable or Turn OFF Bluetooth


 In android, we can disable or turn off Bluetooth just by invoking
a BluetoothAdapter method disable().
 Following is the code snippet to disable or turn off Bluetooth in android applications
using disable() function.

 BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();


bAdapter.disable();
 As we discussed in previous tutorial Android Bluetooth with Examples, we need to set Bluetooth
permissions in our android manifest file as shown below to use Bluetooth features in our android
applications.

 <manifest ... >


<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
...
 </manifest>

BluetoothAdapter class
By the help of BluetoothAdapter class, we can perform fundamental tasks such as initiate device
discovery, query a list of paired (bonded) devices, create a BluetoothServerSocket instance to listen for
connection requests etc.

Constants of BluetoothAdapter class


BluetoothAdapter class provides many constants. Some of them are as follows:

 String ACTION_REQUEST_ENABLE
 String ACTION_REQUEST_DISCOVERABLE
 String ACTION_DISCOVERY_STARTED
 String ACTION_DISCOVERY_FINISHED

Methods of BluetoothAdapter class


Commonly used methods of BluetoothAdapter class are as follows:
 static synchronized BluetoothAdapter getDefaultAdapter() returns the instance of
BluetoothAdapter.
 boolean enable() enables the bluetooth adapter if it is disabled.
 boolean isEnabled() returns true if the bluetooth adapter is enabled.
 boolean disable() disables the bluetooth adapter if it is enabled.
 String getName() returns the name of the bluetooth adapter.
 boolean setName(String name) changes the bluetooth name.
 int getState() returns the current state of the local bluetooth adapter.
 Set<BluetoothDevice> getBondedDevices() returns a set of paired (bonded) BluetoothDevice
objects.
 boolean startDiscovery() starts the discovery process.

Example to make bluetooth enable/disable on single button click


activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">

<Button
android:id="@+id/BtBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Click" />

<TextView
android:id="@+id/BtTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/BtBtn"
android:layout_centerHorizontal="true"
android:hint="Bluetooth Status"
android:textSize="30sp" />

</RelativeLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wifi">

<!--Put the permissions between the manifest and application opening tags-->
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

MainActivity.java
import android.bluetooth.BluetoothAdapter
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

public class MainActivity extends AppCompatActivity


{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btnBt = findViewById(R.id.BtBtn) ;


TextView tvBt = findViewById (R.id.BtTv) ;

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter() ;

btnBt.setOnClickListener (new View.onClickListener() {


public void onClick(View v)
{
if (mBluetoothAdapter.isEnabled())
{
mBluetoothAdapter.disable() ;
tvBt.text = "Bluetooth is OFF";
}
else
{
mBluetoothAdapter.enable() ;
tvBt.text = "Bluetooth is ON";
}
}
});
}
}

Android Bluetooth Example: enable, disable and make discovrable bluetooth programmatically
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">

<Button
android:id="@+id/btnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/btnDiscoverable"
android:text="Turn ON" />

<Button
android:id="@+id/btnDiscoverable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="Discoverable" />

<Button
android:id="@+id/btnOFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/btnDiscoverable"
android:text="Turn OFF" />

</RelativeLayout>

Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
package="com.example.bluetooth"
android:versionCode="1"
android:versionName="1.0" >

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


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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.bluetooth.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

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


</intent-filter>
</activity>
</application>
</manifest>

MainActivity.java
package com.example.bluetooth;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


int REQUEST_ENABLE_BT = 0;
int REQUEST_DISCOVERABLE_BT = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView out=(TextView)findViewById(R.id.out);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
out.append("device not supported");
}
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!mBluetoothAdapter.isDiscovering()) {
Toast.makeText(getApplicationContext(), "MAKING YOUR DEVICE DISCOVERABLE",
Toast.LENGTH_LONG).show();

Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE)


;
startActivityForResult(enableBtIntent, REQUEST_DISCOVERABLE_BT);

}
}
});
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mBluetoothAdapter.disable();
//out.append("TURN_OFF BLUETOOTH");
Toast.makeText(getApplicationContext(), "TURNING_OFF BLUETOOTH", Toast.LENGTH_LO
NG).show();

}
});
}

5.8 SQLite
 SQLite is a Structure query base database, open source, light weight, no network access and
standalone database. It support embedded relational database features.

 The main package is android.database.sqlite that contains the classes to manage your own
databases.
 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.
 SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
 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 Stud

_rec(Username VARCHAR, Password VARCHAR);");

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

 We can retrieve anything from database using an object of the Cursor class.
Cursor resultSet = mydatbase.rawQuery("Select * from Stud_rec",null);
resultSet.moveToFirst();
String username = resultSet.getString(0);
String password = resultSet.getString(1);

 Methods of Cursor
getColumnCount()
This method return the total number of columns of the table.

getColumnIndex(String columnName)
This method returns the index number of a column by specifying the name of the column

getColumnName(int columnIndex)
This method returns the name of the column by specifying the index of the column

getColumnNames()
This method returns the array of all the column names of the table.

getCount()
This method returns the total number of rows in the cursor

Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">

<TextView
android:text="Insert Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:id="@+id/textView"
android:gravity="center"
android:textSize="20dp"
android:textColor="#000000"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="ID"
android:id="@+id/editid"
android:layout_below="@+id/textView"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Name"
android:id="@+id/editname"
android:layout_below="@+id/editid"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Mobile No."
android:id="@+id/editmobile"
android:layout_below="@+id/editname"/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Address"
android:lines="3"
android:id="@+id/editaddress"
android:layout_below="@+id/editmobile"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Pin Code"
android:id="@+id/editpincode"
android:layout_below="@+id/editaddress"/>
<Button
android:text="Insert Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editpincode"
android:layout_centerHorizontal="true"
android:id="@+id/button" />

<TextView
android:text="Search Customer Details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:layout_centerHorizontal="true"
android:id="@+id/textView1"
android:gravity="center"
android:textSize="20dp"
android:layout_below="@+id/button"
android:textColor="#000000"/>

<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter ID"
android:id="@+id/editsearchid"
android:layout_below="@+id/textView1"/>
<Button
android:text="Search Data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/editsearchid"
android:layout_centerHorizontal="true"
android:id="@+id/button1" />
</RelativeLayout>

MainActivity.java
package com.example.dbdemo5;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.example.dbdemo5.databinding.ActivityMainBinding;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

SQLiteDatabase sqLiteDatabaseObj;
EditText editTextID, editTextName, editMobileNo, editAddress, editPincode, editSearchid;
String cid, cname, cmobile, caddress, cpincode, sql_query, sid;
Button EnterData, SearchData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EnterData = (Button)findViewById(R.id.button);
SearchData = (Button)findViewById(R.id.button1);
editTextID = (EditText)findViewById(R.id.editid);
editTextName = (EditText)findViewById(R.id.editname);
editMobileNo = (EditText)findViewById(R.id.editmobile);
editAddress = (EditText)findViewById(R.id.editaddress);
editPincode = (EditText)findViewById(R.id.editpincode);
editSearchid = (EditText)findViewById(R.id.editsearchid);

EnterData.setOnClickListener(new View.OnClickListener() {

public void onClick(View view) {


sqLiteDatabaseObj = openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
sqLiteDatabaseObj.execSQL("CREATE TABLE IF NOT EXISTS cTable(cid
VARCHAR,name VARCHAR,mobile VARCHAR,address VARCHAR,pincode VARCHAR);");
cid = editTextID.getText().toString();
cname = editTextName.getText().toString() ;
cmobile = editMobileNo.getText().toString();
caddress = editAddress.getText().toString();
cpincode = editPincode.getText().toString();
sql_query = "INSERT INTO cTable(cid, name, mobile, address, pincode)
VALUES('"+cid+"', '"+cname+"', '"+cmobile+"', '"+caddress+"', '"+cpincode+"');";
sqLiteDatabaseObj.execSQL(sql_query);
Toast.makeText(getApplicationContext(), "Data Inserted
Successfully",Toast.LENGTH_LONG).show();
}
});

SearchData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sid = editSearchid.getText().toString();
Cursor cursor = sqLiteDatabaseObj.rawQuery( "select * from cTable where cid="+sid+"",
null );
if(cursor.getCount()==0)
Toast.makeText(MainActivity.this, "No Record found",
Toast.LENGTH_SHORT).show();
else {
StringBuffer buffer = new StringBuffer();
while (cursor.moveToNext()) {
String cid = cursor.getString(0);
String name = cursor.getString(1);
String mob = cursor.getString(2);
String addr = cursor.getString(3);
String pcode = cursor.getString(4);
buffer.append(cid + " " + name + " " + mob + " " + addr + " " + pcode + "\n");
Toast.makeText(getApplicationContext(), buffer, Toast.LENGTH_LONG).show();
}
}
}
});
}
}

You might also like