Unit-5_Activity_Mulitmedia with Databases
Unit-5_Activity_Mulitmedia with Databases
The process of taking user from one application to another is achieved by passing the Intent to the
system.
1. Starting an Activity
2. Starting a Service
3. Delivering a broadcast
Intent
1. Starting an Activity
The Intent describes the activity to start and carries any necessary data.
Intent
1. Starting an Activity
Intent : is a messaging object that request an action from another app component.
A Service is a component that performs operations in the background without a user interface.
The Intent describes Service to start and carries any necessary data.
Intent
3. Delivering a broadcast
The system delivers various broadcasts for system events, such as when the system boots up or the
device starts charging.
1. Explicit Intent
2. Implicit Intent
Intent Types
1. Explicit Intent
When intent specifies which component of which application will satisfy the intent, by specifying
a full ComponentName.
You will typically use an explicit intent to start a component in you own app, because you know
the class name of the activity or service you want to start.
For example, you might start a new activity within your app in response to a user action, or start a
service to download a file in background.
Intent Types
1. Explicit Intent
activity_main.xml
Intent Types
1. Explicit Intent
activity_second.xml
Intent Types
1. Explicit Intent
MainActivity.java
Intent Types Creating second activity
3. Select New->Activity->Empty
Views Activity.
When intent do not name a specific component, but instead declare a general action to perform,
which allows a component from another app to handle it.
For example, if you want to show the user a location on a map, you can use an implicit intent to request
that another capable app show a specifies location on map.
When you use an implicit intent, the Android system finds the appropriate component to start by
comparing contents of the intent to intents filters declared in the Manifest file of other apps on the
device.
If the intent matches an intent filter, the system starts that component and delivers it the Intent object.
If multiple filters are compatible, the system displays a dialog so the user can pick up which app to use.
Intent Types
2. Implicit Intent
Intent Types
2. Implicit Intent
Intent Types
2. Implicit Intent
To specify action usually action constants defined by Intent Class are used.
You can specify action for an intent by using setAction() or by Intent Constructor.
Intent Types
2. Implicit Intent
2. The android system searches 3. When a match found, the system starts
all apps for an intent filter that activity (Activity B) by invoking its onCreate()
matches the intent. method and passing it the Intent.
Intent Filters
To advertise which implicit intents your app can receive, you need to declare one or more intent
filters for each of your app components with an <intent-filter> element in your manifest file.
Each intent filter specifies the type of intents it accepts based on the intent’s action, data and
category.
The system delivers an implicit intent to your app component only if the intent can pass
through one of your intent filter.
The app component should declare separate filters for each unique job it can do.
For example, one activity in an image gallery app may have two filters: one filter to view an image,
and another filter to edit an image. When activity starts, it inspects the Intent and decides how to
behave based on the information in the Intent.
Intent Filters
Inside the <intent-filter>, you can specify the type of intents to accept using one or more of
these three elements.
1. <action>
Declares the intent action accepted, in the name attribute. The value must be the literal string value
of an action.
Intent Filters
2. <data>
Declares the type of data accepted, using one or more attributes that specify various aspects of the data
URI(scheme, host, port, path) and MIME type.
<scheme>://<host>:<port>[path]
Intent Filters
2. <data>
Android:mimeType=“”
It is a media type or content type and used to identify the format of a file or content.
Declares the intent category accepted, in the name attribute. The value must be the literal string
value of an action.
It provides additional information about the kind of action or interaction the component is designed
to support.
This is used to indicate that component is a main entry point for the application.
<category android:name="android.intent.category.BROWSABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
This is the default category, if you don’t explicitly specify a category.
Intent Filters
For Example, here is activity declaration with an intent filter to receive an ACTION_SEND intent when
the data type is text.
Activity Life Cycle
The life cycle of an Android application is strictly managed by the system, based on the user’s
needs, available resources, and so on.
A user may want to launch a web browser, for example, but the system ultimately decides whether
to start the application.
Although the system is the ultimate manager, it adheres to some defined and logical guidelines to
determine whether an application can be loaded, paused, or stopped.
If the user is currently working with an activity, the system gives high priority to that application.
Conversely, if an activity is not visible and the system determines that an application must be shut
down to free up resources, it shuts down the lower-priority application.
Activity Life Cycle
The processes running your Android application and its components go through various life-cycle
events, and Android provides callbacks that you can implement to handle state changes.
Here, we get everything ready for the app, including the UI (such as calling setContentView), graphics,
and sound etc.
onStart()
This method pushes the activity into a visible state. In other words this method starts visible
lifecycle of the activity.
This method can also be called when the activity is shown after being hidden first, because another
activity has come to the top of the visibility stack.
Called after the onRestart(), which itself is triggered after the onStop().
Activity Life Cycle
onResume()
onResume() to having the activity fully visible. This is also start of Foreground lifecycle.
In foreground lifecycle the activity can move between onResume() and onPause() multiple times as
other activities, notifications, dialogs with more urgency come on top and go.
This method runs after onStart() but can also be entered (most logically) after our activity is resumed
after being previously paused.
We might reload previously saved user data (such as an important note) from when the app was
interrupted, perhaps by a phone call or the user running another app.
Activity Life Cycle
onPause()
This occurs when our activity is pausing and is about to go into background.
Here, we might save unsaved data (such as the note) that could be reloaded in onResume().
Activities always transition into a paused state when another UI element is displayed on top of the
current activity (for example, a pop-up dialog)
When the activity is about to be stopped (for example, when the user navigates to a different activity).
Activity Life Cycle
onStop()
This relates to the stopping phase. It moves the activity from partially visible to the background state
while keeping all of the view hierarchy intact.
This activity can be taken back to the visible cycle by calling onStart().
This is where we might undo everything we did in onCreate, such as releasing system resources or
writing information to a database.
This method is called when the activity transitions from background state to partially visible state , i.e.
going from onStop() to onStart();
onDestroy()
If we reach here, we will be going through the lifecycle phases from the beginning next time.
It can be called explicitly by user, activity can close involuntary, by system when it needs memory.
Activity Life Cycle Example
@Override
protected void onPause()
public class MainActivity extends AppCompatActivity { {
super.onPause();
@Override Toast.makeText(this,"onPause", Toast.LENGTH_LONG).show();
protected void onCreate(Bundle savedInstanceState) { }
super.onCreate(savedInstanceState); @Override
setContentView(R.layout.activity_main); protected void onStop()
Toast.makeText(this,"onCreate", Toast.LENGTH_LONG).show(); {
super.onStop();
} Toast.makeText(this,"onStop", Toast.LENGTH_LONG).show();
@Override }
protected void onStart() @Override
{ protected void onRestart()
super.onStart(); {
Toast.makeText(this,"onStart", Toast.LENGTH_LONG).show(); super.onRestart();
} Toast.makeText(this,"onRestart", Toast.LENGTH_LONG).show();
@Override }
protected void onResume() @Override
{ protected void onDestroy()
super.onResume(); {
Toast.makeText(this,"onResume", Toast.LENGTH_LONG).show(); super.onDestroy();
} Toast.makeText(this,"onDestroy", Toast.LENGTH_LONG).show();
}
}
MainActivity.java
Broadcast Life Cycle
Broadcast Receiver
Broadcast receivers simply respond to broadcast messages from other applications or from the
system itself.
For example, application can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and available for them to use.
These kind broadcast can be sent for various events like when the device is charging, wi-fi is connected,
screen is turned off, device booted etc.
So the broadcast receiver who will intercept this communication and will initiate the appropriate action.
Broadcast Life Cycle
There are two important steps to make broadcast receiver that works for the system,
The onReceive() method contains action to be performed when the broadcast is received.
1. Creating Broadcast Receiver for handling Power Source Connected /Disconnected
PowerReceiver.java
Broadcast Life Cycle
2. Registering the Broadcast Receiver
Static Registration
This method registers the receiver to listen for specific system-wide broadcasts even when your
app is not running.
If you want to register the receiver at runtime, use the registerReceiver() method.
This method requires a BroadcastReceiver instance and an IntentFilter to specify the type of
broadcast you want to listen for.
Dynamic Registration (In Java Code)
Broadcast Life Cycle
Broadcasting an Intent
You can create such custom actions like above and listen for them in your receiver.
Broadcast Life Cycle
Android Broadcast
System Receiver
Broadcast Receiver, receives messages (events or intents) generated by system or other application to
which it was registered.
Broadcast Life Cycle
System Level Broadcasts
These broadcasts are sent by system to notify apps about various events or system changes.
These broadcasts are sent by system to notify apps about various events or system changes.
It facilitate other applications to securely access and modifies that data based on the user requirement.
There are six abstract methods which are essential to override as the a part of Content Provider.
Once started, a service might continue running for some time, even after the user switches to another
application.
For example,
Service can handle network transaction, play music, perform file I/O, or interact with content provider etc.
Features of Services
2. Runs independently
Runs on its own thread, independent of main UI thread.
3. Life Span
Services can run indefinitely, even when the application is not in the foreground, until explicitly stopped.
Bound
A service is bound when an application component binds to it by
2 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).
Service Lifecycle
To create a service, you create a Java class that extends the Service base class or one of its existing
subclasses.
The Service base class defines various callback methods and the most important are given below.
You don't need to implement all the callbacks methods. However, it's important that you understand each
one and implement those that ensure your app behaves the way users expect.
Service Lifecycle
Sr.No. Callback & Description
onStartCommand()
The system calls this method when another component, such as an activity, requests that
the service be started, by calling startService(). If you implement this method, it is your
1
responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
onBind()
The system calls this method when another component wants to bind with the service by
calling bindService(). If you implement this method, you must provide an interface that
2 clients use to communicate with the service, by returning an IBinder object. You must
always implement this method, but if you don't want to allow binding, then you should
return null.
onUnbind()
3 The system calls this method when all clients have disconnected from a particular
interface published by the service.
Service Lifecycle
onCreate()
The system calls this method when the service is first created
5 using onStartCommand() or onBind(). This call is required to perform one-time set-
up.
onDestroy()
The system calls this method when the service is no longer used and is being
6 destroyed. Your service should implement this to clean up any resources such as
threads, registered listeners, receivers, etc.
Example of Service
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Example of Service"
android:gravity="center"
android:textSize="30sp"/>
<Button
android:id="@+id/startService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:textSize="25sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>
<Button
android:id="@+id/stopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:textSize="25sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>
</LinearLayout> activity_main.xml
public class ExampleService extends Service {
@Override
public void onCreate(){
super.onCreate();
//Initialize Resource
}
@Override
public int onStartCommand(Intent intent,int flag, int startId)
{
//do background task here
Toast.makeText(getApplicationContext(),"Service Started",Toast.LENGTH_LONG).show();
return START_STICKY; //restart the service, if it is get killed.
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
public void onDestroy()
{
//release resources
super.onDestroy();
Toast.makeText(getApplicationContext(),"Service Stopped",Toast.LENGTH_LONG).show();
}
} ExampleService.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart=(Button)findViewById(R.id.startService);
Button btnStop=(Button)findViewById(R.id.stopService);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,ExampleService.class);
startService(intent);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,ExampleService.class);
stopService(intent);
}
});
}
}
MainActivity.java
<application>
<service android:name=".ExampleService"/>
</application>
AndroidManifest.xml
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Ringtone Service"
android:gravity="center"
android:textSize="30sp"/>
<Button
android:id="@+id/startService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Service"
android:textSize="25sp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>
<Button
android:id="@+id/stopService"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Stop Service"
android:textSize="25sp" activity_main.xml
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"/>
public class RingtoneService extends Service {
private Ringtone ringtone;
@Override
public void onCreate(){
super.onCreate();
Uri ringtoneUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
ringtone=RingtoneManager.getRingtone(getApplicationContext(),ringtoneUri);
}
@Override
public int onStartCommand(Intent intent,int flag, int startId)
{
if(ringtone!=null && !ringtone.isPlaying())
{
ringtone.play();
}
return START_STICKY; //restart the service, if it is get killed.
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
public void onDestroy()
{
//release resources
super.onDestroy();
if(ringtone!=null && ringtone.isPlaying())
{
ringtone.stop();
}
}
}
RingtoneService.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnStart=(Button)findViewById(R.id.startService); <service android:name=".RingtoneService"/>
Button btnStop=(Button)findViewById(R.id.stopService); </application>
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,RingtoneService.class);
stopService(intent);
}
});
}
}
MainActivity.java
Multimedia Framework
The android multimedia system includes multimedia applications, multimedia frameworks,
OpenCore engine and hardware for audio/video input/output devices.
The goal of the android multimedia framework is to provide a reliable interface for java services.
The multimedia framework consists of several core dynamic libraries such as libmediajni,
libmedia, libmediaplayservice.
Multimedia Framework
It refers to the core library (written in C / C++) responsible for fundamental media functionalities like
playback and recording.
media_jni
It act as bridge between the Java Media framework and the native libmedia library, allowing java
code to interact with media operations through JNI.
Media server
A system level process responsible for managing media decoding, playback, streaming.
Provides access various codecs to handle different file formats.
Media Player
A java class within the android SDK that used to control media playback in apps.
Offers functionalities like play, pause, stop, seek and manage playback events.
Can play both video and audio files from the local storage as well as network stream.
Multimedia Framework
How does it work?
When Java application in Android wants to perform a media operation(like playing a video/audio), it calls to
a method in Java Media framework.
This Java method then invokes a native function within the “media_jni” layer.
“media_jni” then communicates with the appropriate functions in libmedia to execute the media
operation on the native level.
Then PVPlayer processes the media data stream with the steps:
1. MediaPalyer : This class is the primary API for playing audio and video.
2. AudioManager: This class manages audio sources and audio output on a device. It mostly
support volume and ringer related services.
Play Audio and Video
Using the Media APIs Android supports playing audio and video content under the android.media
package.
The MediaPlayer class is responsible for playing both audio and video content.
The content for this class can come from the following sources:
Web: You can play content from the Web via a URL.
.apk file: You can play content that is packaged as part of your .apk file.
The Storage Access Framework, which provides access to media files stored across a range of
providers and internet services.
SD card: You can play content that resides on the device’s SD card or emulated local storage.
Play <TextView <Button
android:layout_width="match_parent" android:id="@+id/pause"
Audio android:layout_height="wrap_content" android:layout_width="200dp"
android:text="Audio Player" android:layout_height="wrap_content"
android:textSize="40sp" android:text="Pause"
android:textStyle="bold" android:textSize="35sp"
android:gravity="center"/> android:layout_gravity="center"/>
<Button </LinearLayout>
android:id="@+id/play"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Play"
android:textSize="35sp"
android:layout_gravity="center"/>
<Button
android:id="@+id/stop"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Stop"
android:textSize="35sp"
android:layout_gravity="center"/>
activity_main.xml
Play Audio
mediaPlayer.start();
}
});
MainActivity.java
Play Video
<TextView
<Button
android:layout_width="match_parent"
android:id="@+id/pause"
android:layout_height="wrap_content"
android:layout_width="150dp"
android:text="Media Player"
android:layout_height="wrap_content"
android:textSize="20sp"
android:text="Pause"
android:gravity="center"
android:textSize="20sp"
android:textStyle="bold"/>
android:layout_gravity="center"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
<VideoView
android:layout_height="wrap_content"
android:id="@+id/video"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_gravity="center">
android:layout_height="600dp"/>
<Button
</LinearLayout>
android:id="@+id/play"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Play"
android:textSize="20sp" activity_main.xml
android:layout_gravity="center"
android:layout_marginRight="20dp"/>
public class MainActivity extends AppCompatActivity { Play Video
@Override
protected void onCreate(Bundle savedInstanceState) { play.setOnClickListener(new View.OnClickListener() {
super.onCreate(savedInstanceState); @Override
setContentView(R.layout.activity_main); public void onClick(View view) {
Button play=(Button) findViewById(R.id.play);
Button pause=(Button)findViewById(R.id.pause) ; videoView.start();
VideoView videoView=(VideoView) findViewById(R.id.video); Toast.makeText(getApplicationContext(),
"Playing",Toast.LENGTH_LONG).show();
String videoPath="android.resource://"+getPackageName()+ }
"/"+(R.raw.sample_video); });
Uri videoUri= Uri.parse(videoPath); pause.setOnClickListener(new View.OnClickListener() {
videoView.setVideoURI(videoUri); @Override
public void onClick(View view) {
videoView.pause();
Toast.makeText(getApplicationContext(),
"Paused",Toast.LENGTH_LONG).show();
}
});
}
}
MainActivity.java
Play Video
Text To Speech
TextToSpeech android feature synthesizes speech from text for immediate playback or to
create a sound file.
In android, by using TextToSpeech class we can easily convert our text into voice and it
supports different types of speaking languages.
We can choose the speaking language based on our requirements in the android
application.
The android TextToSpeech instance can only be used to synthesize text once it has
completed its initialization so implement TextToSpeech.
OnInitListener to notify the completion of initialization. During the initialization, we can set the
audio pitch rate, audio speed, type of language to speak, etc. based on our requirements.
Text To Speech
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Text To Speech"
android:textSize="25sp"
android:textStyle="bold"
android:gravity="center"
android:layout_marginBottom="20dp"/>
<EditText
android:id="@+id/etspeak"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="Type to Listen"
android:textSize="25sp"
android:layout_marginBottom="20dp"/>
<Button
activity_main.xml android:id="@+id/speak"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Speak"
android:textSize="25dp"
android:layout_gravity="center"/>
</LinearLayout>
public class MainActivity extends AppCompatActivity { Text To Speech
Button speakButton; speakButton.setOnClickListener(new View.OnClickListener() {
EditText etSpeak; @Override
TextToSpeech tts; public void onClick(View v) {
@Override tts.speak(etSpeak.getText().toString(),TextToSpeech.QUEUE_FLUSH,
protected void onCreate(Bundle savedInstanceState) { null);
super.onCreate(savedInstanceState); }
setContentView(R.layout.activity_main); });
}
speakButton=(Button) findViewById(R.id.speak); }
etSpeak=(EditText) findViewById(R.id.etspeak); MainActivity.java
}
});
Text To Speech
Sensors
Most Android-powered devices have built-in sensors that measure motion, orientation, and various
environmental conditions.
These sensors are capable of providing raw data with high precision and accuracy.
These are useful, if you want to monitor three-dimensional device movement or positioning, or
you want to monitor changes in the ambient environment near a device.
For example,
A game might track readings from a device's gravity sensor to infer complex user
gestures and motions, such as tilt, shake, rotation, or swing.
Sensors
The Android platform supports three broad categories of sensors:
Motion sensors
These sensors measure acceleration forces and rotational forces along three axes. This category
includes accelerometers, gravity sensors, gyroscopes, and rotational vector sensors.
Environmental sensors
These sensors measure various environmental parameters, such as ambient air temperature and
pressure, illumination, and humidity. This category includes barometers, photometers, and
thermometers.
Position sensors
These sensors measure the physical position of a device. This category includes orientation
sensors and magnetometers.
Sensors
The Android sensor framework lets you access many types of sensors. Some of these sensors are hardware-
based and some are software-based.
Sensors
Sensors
Sensors
Ex. Android Application to display list of available sensors on a device.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List of Sensors"
android:textSize="25sp"
android:textStyle="bold"
android:gravity="center"/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
activity_main.xml
Sensors
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView) findViewById(R.id.listView);
SensorManager sm=(SensorManager)getSystemService(SENSOR_SERVICE);
List <Sensor>sensorList=sm.getSensorList(Sensor.TYPE_ALL);
First thing is you have instantiate the object of class SensorManager as,
SensorManager sm=(SensorManager)getSysteService(SENSOR_SERVICE);
Sensor accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensors
Ex. Android Program to change background color on device shuffle.
Once sensor declaration is over, you need register the sensor listener and override two methods
as follows,
Registering Sensor:
sm.registerListener(this, accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
sm.registerListener(SensorListener listener, Sensor sensor, int rate);
@Override:
Finally, we unregister the registered sensor during onPause() / onStop(), in order release the sources
and save battery life.
Un-registering Sensor:
super.onPause();
unregisterListener( SensorListener listener, Sensor sensor);
}
Ex. Android Program to change background color on device shuffle.
public class MainActivity extends AppCompatActivity implements SensorEventListener {
SensorManager sm;
Sensor accelerometer;
float lastX,lastY,lastZ;
View view;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.tv);
view=(View)findViewById(R.id.main);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
@Override
public void onResume()
{
super.onResume();
sm.registerListener(this,accelerometer,SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void onSensorChanged(SensorEvent event)
{
if(event.sensor.getType()!=Sensor.TYPE_ACCELEROMETER)
{
return;
}
float x=event.values[0];
@Override float y=event.values[1];
public void onPause() float z=event.values[2];
{ String values="X:"+x+"\n"+"Y:"+y+"\n"+"Z:"+z;
super.onPause(); tv.setText(values);
sm.unregisterListener(this);
} float movement=Math.abs(x+y+z-lastX-lastY-lastZ);
if(movement>10)
{
changeColor();
}
lastX=x;
lastY=y;
lastZ=z;
}
public void changeColor()
{
view.setBackgroundColor(Color.parseColor("#FF8DA1”));
}
@Override
public void onAccuracyChanged(Sensor sensor, int
accuracy)
{
}
}
Camera
The Android framework includes support for various cameras and camera features available on
devices, allowing you to capture pictures and videos in your applications.
The Android framework supports capturing images and video through android.hardware.camera2 API
or camera Intent.
Camera
Here are the relevant classes:
android.hardware.camera2
This package is the primary API for controlling device cameras. It can be used to take pictures or
videos when you are building a camera application.
Camera
This class is the older deprecated API for controlling device cameras.
SurfaceView
This class is used to present a live camera preview to the user.
MediaRecorder
This class is used to record video from the camera.
Intent
• Camera Permission - Your application must request permission to use a device camera.
• Camera Features - Your application must also declare use of camera features, for example
• Storage Permission - Your application can save images or videos to the device's external storage (SD
Card) if it targets Android 10 (API level 29) or lower and specifies the following in the manifest.
• Location Permission - If your application tags images with GPS location information, you must request
the ACCESS_FINE_LOCATION permission.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Camera Application"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold"/>
<ImageView
android:id="@+id/imgview"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="15dp"/>
<Button
android:id="@+id/camOpen"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center|bottom"
android:text="Open_Camera"
android:textSize="20sp"/>
</LinearLayout>
activity_main.xml
Building a camera app
AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA"/>
Recording Video
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Camera Application"
android:gravity="center"
android:textSize="25sp"
android:textStyle="bold"/>
<VideoView
android:id="@+id/videoview"
android:layout_width="match_parent"
android:layout_height="550dp"
android:layout_marginBottom="15dp"/>
<Button
android:id="@+id/camOpen"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_gravity="center|bottom"
android:text="Record/Play Video"
android:textSize="20sp"/>
</LinearLayout>
activity_main.xml
Recording Video
VideoView videoView;
Button openCamera;
int CAMERA_REQUEST=100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
videoView=(VideoView)findViewById(R.id.videoview);
openCamera=(Button)findViewById(R.id.camOpen);
AndroidManifest.xml
The app framework provides access to the Bluetooth functionality through Bluetooth APIs.
These APIs let apps connect to other Bluetooth devices, enabling point-to-point and multipoint
wireless features.
luetooth
Using the Bluetooth APIs, an app can perform the following:
For Bluetooth-enabled devices to transmit data between each other, they must first form a channel of
communication using a pairing process.
One device, a discoverable device, makes itself available for incoming connection requests. Another
device finds the discoverable device using a service discovery process.
After the discoverable device accepts the pairing request, the two devices complete a bonding process
in which they exchange security keys.
After the pairing and bonding processes are complete, the two devices exchange information.
Ex. Android Program to Turn ON, Turn OFF, List available devices,
luetooth get visible/discoverable.
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Demo" <Button
android:textSize="25sp" android:layout_width="match_parent"
android:textStyle="bold" android:layout_height="wrap_content"
android:gravity="center"/> android:text="Discover"
android:textSize="20sp"
<Button android:id="@+id/discover"
android:layout_width="match_parent" android:gravity="center"/>
android:layout_height="wrap_content"
android:text="Turn ON" <Button
android:textSize="20sp" android:layout_width="match_parent"
android:id="@+id/turnOn" android:layout_height="wrap_content"
android:gravity="center"/> android:text="List"
android:textSize="20sp"
<Button android:id="@+id/list"
android:layout_width="match_parent" android:gravity="center"/>
android:layout_height="wrap_content"
android:text="Turn OFF" </LinearLayout>
android:textSize="20sp"
android:id="@+id/turnOff"
android:gravity="center"/>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonTurnOn=findViewById(R.id.turnOn);
buttonTurnOff=findViewById(R.id.turnOff);
buttonDiscover=findViewById(R.id.discover);
buttonList=findViewById(R.id.list);
lv=findViewById(R.id.lv);
bAdapter=BluetoothAdapter.getDefaultAdapter();
buttonTurnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/*if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT},BluetoothRequest);
}*/
//above code needed when android version is greater than 11(android 12+).
if(bAdapter==null)
{
Toast.makeText(MainActivity.this,
"Bluetooth Not Supported by Device",Toast.LENGTH_LONG).show();
}
else if(!bAdapter.isEnabled())
{
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
Toast.makeText(MainActivity.this,
"Bluetooth Turning ON",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,
"Already Turned ON",Toast.LENGTH_LONG).show();
}
}
});
buttonTurnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(bAdapter!=null&&bAdapter.isEnabled())
{
/*Intent intent=new Intent(Settings.ACTION_BLUETOOTH_SETTINGS);
startActivity(intent);*/
//above code needed when android version is greater than 11(android 12+).
Toast.makeText(MainActivity.this,
"Turning OFF",Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,
"Already Turned OFF",Toast.LENGTH_LONG).show();
}
}
});
buttonDiscover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT},BluetoothRequest);
}*/
//above code needed when android version is greater than 11.
Intent intentDiscoverable=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(intentDiscoverable);
Toast.makeText(MainActivity.this,
"Device is now Discoverable",Toast.LENGTH_LONG).show();
}
});
buttonList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/*if(ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.BLUETOOTH_CONNECT)
!=PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT},BluetoothRequest);
}*/
//above code need when android version is greater than 11.
Set<BluetoothDevice> deviceList=bAdapter.getBondedDevices();
List<String>deviceNames=new ArrayList<String>();
for(BluetoothDevice device:deviceList)
{
deviceNames.add(device.getName());
}
ArrayAdapter<String>adapter=new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_expandable_list_item_1,deviceNames);
lv.setAdapter(adapter);
}
});
AndroidManifest.xml
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-feature android:name="android.hardware.bluetooth"/>
Animation
Animation is process of adding motion, effects to any view, image or text.
We can write XML animations and then load and play them in Java, on a specific UI widget.
Animation
Fade IN and OUT
Alpha is a measure of transparency, by stating the starting fromAlpha and ending toAlpha values, we
can fade items in and out.
A value 0.0 is invisible and 1.0 is an object’s normal appearance. Steadily moving between the two
makes a fading effect.
Fade IN
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Animation Demo"
android:textSize="25sp"
android:textStyle="bold"
android:gravity="center"
/>
<ImageView
android:id="@+id/img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/logo"
/>
<Button
android:id="@+id/fadeIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fade In "
android:textSize="25sp"/>
</LinearLayout>
Activity_main.xml
Fade IN
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
android:fromAlpha="0.0"
android:duration="8000"
android:toAlpha="1.0"/>
</set>
fadein.xml
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize it
animFadeIn= AnimationUtils.loadAnimation(this,R.anim.fadein);
btnFadeIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
img.startAnimation(animFadeIn);
}
});
}
}
Fade OUT
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView img=(ImageView) findViewById(R.id.img);
Button btnFadeIn=(Button)findViewById(R.id.fadeIn);
Button btnFadeOut=(Button)findViewById(R.id.fadeOut);
//Declare an animation object.
Animation animFadeIn, animFadeOut;
//Initialize it
animFadeIn= AnimationUtils.loadAnimation(this,R.anim.fadein);
animFadeOut= AnimationUtils.loadAnimation(this,R.anim.fadeout);
btnFadeIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
img.startAnimation(animFadeIn);
}
});
btnFadeOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnFadeOut.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animFadeOut);
}
});
}} Fade OUT
Animation
Zoom IN and OUT
By using Scale value we can control its X direction and Y direction scaling.
If we increase both the values uniformly then it appears to be Zoomed IN and if decreased uniformly it
appears to be Zoomed OUT.
So, starting fromXScale and ending toXScale values creates Zoom animation effect.
The pivotX and pivotY defines the pivot point against which we are going to zoom.
Zoom In
btnZoomIn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnZoomIn.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animZoomIn);
}
});
Zoom Out
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<scale android:fromXScale="6"
android:fromYScale="6"
android:pivotX="50%"
android:pivotY="50%"
android:duration="8000"
android:toXScale="1"
android:toYScale="1"
/>
</set>
zoomout.xml
btnZoomout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnZoomout.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animZoomOut);
}
});
Animation
Rotate Clockwise & Anti-Clockwise
By using rotate element of XML we can control the rotation of a view in clockwise or anti clockwise
direction.
The starting fromDegree and ending toDegree help us to rotate the view.
btnRotateClk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnRotateClk.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animRotateClk);
}
});
Rotate Anti Clockwise
btnRotateAntiClk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
btnRotateAntiClk.setBackgroundColor(Color.parseColor("#FD3120"));
img.startAnimation(animRotateAntiClk);
}
});
SQLite Database
SQLite is a data storage available in Android where we can store data in user’s device and can use it
any time when required.
The SQLiteDatabase class is the class that represents the actual database.
It is a helper class for managing SQLite database creation, version management, and database
upgrades.
The subclasses which extends it , are required to override two methods of it onCrearte() and
onUpgrade();
onCreate(): This method is called when the database is created for the first time, allowing you to
create tables and define database schema.
onUpgrade(): This method is called when the database schema version changes, allowing you to
upgrade database to new version without data loss.
SQLite API
Example
public class DBHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="student.db";
private static final int DATABASE_VERSION=1;
public DBHelper(Context context)
{
super(context,DATABASE_NAME,null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
//create table and schema here.
db.execSQL("CREATE TABLE student(id INTEGER PRIMARY KEY AUTOINCREMENT,name TEXT)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//implement database upgrade logic here...!
db.execSQL("DROP TABLE IF EXISTS student"); //deletes existing table “student”
onCreate(db); //called to recreate the database.
}
}
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Student Database Example"
android:textSize="25sp"
android:gravity="center"
android:textStyle="bold"/>
<EditText <Button
android:id="@+id/et1" android:layout_width="160dp"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:layout_height="60dp" android:id="@+id/save"
android:hint="Student Name"/> android:textSize="20sp"
<EditText android:text="Save"/>
android:id="@+id/et2" <Button
android:layout_width="match_parent" android:layout_width="160dp"
android:layout_height="60dp" android:layout_height="wrap_content"
android:inputType="number" android:id="@+id/display"
android:hint="Score Obtained"/> android:textSize="20sp"
android:text="Display"/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/lv"/>
</LinearLayout>
activity_main.xml
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
//implement database upgrade logic here...!
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
public class MainActivity extends AppCompatActivity {
DBHelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et1=(EditText)findViewById(R.id.et1);
EditText et2=(EditText)findViewById(R.id.et2);
Button save=(Button)findViewById(R.id.save);
Button display=(Button)findViewById(R.id.display);
ListView lv=(ListView)findViewById(R.id.lv);
dbHelper=new DBHelper(MainActivity.this);
MainActivity.java
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!et1.getText().toString().isEmpty()&&!et2.getText().toString().isEmpty())
{
String sname = et1.getText().toString();
String str2 = et2.getText().toString();
int marks = Integer.parseInt(str2);
dbHelper.addDetails(sname, marks);
Toast.makeText(MainActivity.this,
"Record Added Successfully", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(MainActivity.this,
"Enter all details",Toast.LENGTH_LONG).show();
}
}
});
MainActivity.java
display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Cursor cursor=dbHelper.displayDetails();
lv.setAdapter(adapter);
}
else{
Toast.makeText(MainActivity.this,
"No Record found",Toast.LENGTH_LONG).show();
}
}
});
}//end onDestroy()
MainActivity.java
@Override
protected void onDestroy() {
super.onDestroy();
// Close the cursor if it's still open
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textName"
android:text="Name"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textScore"
android:text="Score"/>
</LinearLayout>
Thank You