Mad 5th
Mad 5th
DEVELOPMENT
Chapter 5
Miss.P.S.Dungarwal
Lecturer In CM Dept.
S.H.H.J.B.Poly,Chandwad
Android Media Player
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}catch(Exception e){e.printStackTrace();}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Android MediaPlayer Example of
controlling the audio
• activity_main.xml
– Drag three buttons from palette to start, stop and
pause the audio play. Now the xml file will look
like this:
MainActivity.java
package com.example.audioplay;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button start,pause,stop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
//creating media player
final MediaPlayer mp=new MediaPlayer();
try{
//you can change the path, here path is external directory(e
.g. sdcard) /Music/maine.mp3
mp.setDataSource(Environment.getExternalStorageDirectory().g
etPath()+"/Music/maine.mp3");
mp.prepare();
}catch(Exception e){e.printStackTrace();}
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start(); } });
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}
Android Video Player
• 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 setVideoURI (Uri sets the URI of the video file.
uri)
<VideoView
android:id="@+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
Activity class
• Let's write the code of to play the video file. Here, we are going to play 1.mp4 file located
inside the sdcard/media directory.
package com.example.video1;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.MediaController;
import android.widget.VideoView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoView videoView =(VideoView)findViewById(R.id.videoView1);
//Creating MediaController
MediaController mediaController= new MediaController(this);
mediaController.setAnchorView(videoView);
//specify the location of media file
Uri uri=Uri.parse(Environment.getExternalStorageDirectory().getPath
()+"/media/1.mp4");
//Setting MediaController and URI, then starting the videoView
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true; } }
Android Media Recorder
• MediaRecorder class can be used to record
audio and video files.
• After recording the media, we can create a
sound file that can be played later.
• activity_main.xml
– Drag 2 buttons from the palette, one to start the
recording and another stop the recording. Here,
we are registering the view with the listener in xml
file using android:onClick.
<RelativeLayout xmlns:androclass="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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="68dp"
android:layout_marginTop="50dp"
android:text="Start Recording"
android:onClick="startRecording" />
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="64dp"
android:text="Stop Recording"
android:onClick="stopRecording" />
package com.javatpoint.mediarecorder;
import java.io.File;
import java.io.IOException;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
int speak (String text, int converts the text into speech.
queueMode, HashMap params) Queue Mode may be QUEUE_ADD
or QUEUE_FLUSH. Request
parameters can be null,
KEY_PARAM_STREAM,
KEY_PARAM_VALUME etc.
int setSpeechRate(float speed) it sets the speed for the speech.
int setPitch(float speed) it sets the pitch for the speech.
int setLanguage (Locale loc) it sets the locale specific language
for the speech.
void shutdown() it releases the resource set by
TextToSpeech Engine.
int stop() it interrupts the current utterance
(whether played or rendered to
file) and discards other utterances
in the queue.
TextToSpeech.OnInitListener Interface
• You need to implement
TextToSpeech.OnInitListener interface, for
performing event handling on TextToSpeech
engine.
• Method of TextToSpeech.OnInitListener
Interface
– There is only one method in this interface
Method Description
buttonSpeak.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
speakOut();
}
});
}
@Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA|| result == TextToSpeech.LANG_NOT_S
UPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
buttonSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = editText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Android Sensor
• Sensors can be used to monitor the three-
dimensional device movement or change in
the environment of the device.
• Android provides sensor api to work with
different types of sensors.
Types of Sensors
Android supports three types of sensors:
Category Description
Motion Sensors These sensors are useful to measure
acceleration forces and rotational forces
along three axes. This category includes
accelerometers, gravity sensors,
gyroscopes, and rotational vector sensors.
Environmental Sensors These sensors are useful to measure
various environmental parameters, such as
ambient air temperature and pressure,
illumination, and humidity. This category
includes barometers, photometers, and
thermometers.
Position Sensors These sensors are useful to measure the
physical position of a device. This category
includes orientation sensors and
magnetometers.
• The Android sensor framework provided a following classes and interfaces
to access device sensors and acquire raw sensor data.
Class Description
SensorManager By using this class we can create an instance of sensor service
and this class provides a various methods for accessing and
listing sensors, registering and unregistering sensor event
listeners and acquiring orientation information.
• The next thing you need to do is to instantiate the object of Sensor class by
calling the getDefaultSensor() method of the SensorManager class.
Its syntax is given below −
Sensor light;
light=sMgr.getDefaultSensor(Sensor.TYPE_LIGHT);
• Once that sensor is declared , you need to register its listener and override
two methods which are onAccuracyChanged and onSensorChanged. Its
syntax is as follows −
sMgr.registerListener(this,light,SensorManager.SENSOR_DELAY_NORMAL);
public void onAccuracyChanged(Sensor sensor, int accuracy) { }
public void onSensorChanged(SensorEvent event) { }
• Getting list of sensors supported
– You can get a list of sensors supported by your device
by calling the getSensorList method, which will return a
list of sensors containing their name and version
number and much more information. You can then
iterate the list to get the information. Its syntax is given
below −
sMgr=(SensorManager)this.getSystemService(SENSOR_SERVICE
);
List<Sensor> list = sMgr.getSensorList(Sensor.TYPE_ALL);
for(Sensor sensor: list){ }
• Apart from the these methods, there are other methods
provided by the SensorManager class for managing
sensors framework. These methods are listed below −
Sr.No Method & description
1 getDefaultSensor(int type)
This method get the default sensor for a given type.
2 getInclination(float[] I)
This method computes the geomagnetic inclination angle in radians from the
inclination matrix.
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Shake to switch color" />
</RelativeLayout>
import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
}
private void getAccelerometer(SensorEvent event) {
float[] values = event.values;
// Movement
float x = values[0];
float y = values[1];
float z = values[2];
float accelationSquareRoot = (x * x + y * y + z * z)
/ (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);
long actualTime = System.currentTimeMillis();
Toast.makeText(getApplicationContext(),String.valueOf(accelationSquareRoot)+" "+
SensorManager.GRAVITY_EARTH,Toast.LENGTH_SHORT).show();
if (accelationSquareRoot >= 2) //it will be executed if you shuffle
{ if (actualTime - lastUpdate < 200) {
return;
}
lastUpdate = actualTime;//updating lastUpdate for next shuffle
if (isColor) {
view.setBackgroundColor(Color.GREEN);
} else {
view.setBackgroundColor(Color.RED);
}
isColor = !isColor; } }
@Override
protected void onResume() {
super.onResume();
// register this class as a listener for the orientation and
// accelerometer sensors
sensorManager.registerListener(this,sensorManager.getDefaultSe
nsor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
protected void onPause() {
// unregister listener
super.onPause();
sensorManager.unregisterListener(this);
}
}
Android Camera
• Camera is mainly used to capture picture and
video. We can control the camera by using
methods of camera API.
• Android provides the facility to work on camera by
2 ways:
– By Camera Intent
– By Camera API
Using existing android camera application
in our application
• You will use MediaStore.ACTION_IMAGE_CAPTURE to launch an
existing camera application installed on your phone. Its syntax is
given below:-
Intent intent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Sr.No Intent type and description
ACTION_IMAGE_CAPTURE_SECURE
1 It returns the image captured from the camera , when the device is
secured
ACTION_VIDEO_CAPTURE
2 It calls the existing video application in android to capture video
EXTRA_SCREEN_ORIENTATION
3 It is used to set the orientation of the screen to vertical or landscape
EXTRA_FULL_SCREEN
4
It is used to control the user interface of the ViewImage
INTENT_ACTION_VIDEO_CAMERA
5
This intent is used to launch the camera in the video mode
EXTRA_SIZE_LIMIT
6
It is used to specify the size limit of video or image capture size
• Now you will use the function
startActivityForResult() to launch this activity and wait
for its result. Its syntax is given below
startActivityForResult(intent,0);
This method has been defined in the activity class.
We are calling it from main activity. There are
methods defined in the activity class that does the
same job , but used when you are not calling from the
activity but from somewhere else.
Sr.No Activity function description
requestPermissions(newString[]{Manifest.permission.CAMERA},
MY_CAMERA_PERMISSION_CODE)
• startActivityForResult(cameraIntent, CAMERA_REQUEST)
Method:
Now we will call Function startActivityForResult(cameraIntent, CAMERA_REQUEST);
When you start an activity for the result, it request Camera to take a photo then
return it to your calling activity, you pass it a unique integer value or anything you
have not used already in that class. The requestCode helps you to identify from
which Intent you came back.
So, that CAMERA_REQUEST could be any value you define in your class like this:
<uses-permission
android:name="android.permission.RECORD_AUDIO" />
<!-- We will request access to the camera, saying we
require a camera
of some sort but not one with autofocus capability. -->
<uses-permission
android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera"
/>
XML FILE : 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="fill_parent"
android:layout_height="fill_parent >
<Button
android:id="@+id/recording"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Video"/>
<TextView
android:id="@+id/output"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello"/>
</LinearLayout>
import java.io.File;
import java.text.SimpleDateFormat;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class VideocameraActivity extends Activity {
private Uri fileUri;
public static final int MEDIA_TYPE_VIDEO = 2;
private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
public static VideocameraActivity ActivityContext =null;
public static TextView output;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActivityContext = this;
Button buttonRecording = (Button)findViewById(R.id.recording);
output = (TextView)findViewById(R.id.output);
buttonRecording.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0)
{
// create new Intentwith with Standard Intent action that can be sent to have the
camera application capture an video and return it.
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
return Uri.fromFile(getOutputMediaFile(type));
}
if (! mediaStorageDir.mkdirs()){
// For unique file name appending current timeStamp with file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(date.getTime());
File mediaFile;
if(type == MEDIA_TYPE_VIDEO) {
// For unique video file name appending current timeStamp with file name
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"VID_"+ timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
– String ACTION_REQUEST_ENABLE
– String ACTION_REQUEST_DISCOVERABLE
– String ACTION_DISCOVERY_STARTED
– String ACTION_DISCOVERY_FINISHED
Methods of BluetoothAdapter class
• 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.
Android Set Bluetooth Permissions
• To use Bluetooth features in our android applications,
we must need to add multiple permissions, such
as BLUETOOTH and ACCESS_COARSE_LOCATION or ACC
ESS_FINE_LOCATION in our manifest file.
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.
In case if getDefaultAdapter() method returns NULL, then the device does not support Bluetooth and
we can disable all Bluetooth features.
Android Enable or Disable Bluetooth
If Bluetooth is supported but disabled, then isEnabled() method will return false and
we can request user to enable Bluetooth without leaving our application by
using startActivityForResult() method with ACTION_REQUEST_ENABLE intent
action parameter.
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.
Following is the code snippet to enable the system’s discoverable mode to make
sure that the device discoverable to other devices.
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.
Android List Paired Devices
By using 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.
If you observe above code, we are getting the Bluetooth paired devices name
and mac address by using BluetoothDevice object.
<?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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity" android:transitionGroup="true">
<TextView android:text="Bluetooth Example"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/textview"
android:textSize="35dp" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Tutorials point"
android:id="@+id/textView" android:layout_below="@+id/textview"
android:layout_centerHorizontal="true" android:textColor="#ff7aff24"
android:textSize="35dp" />
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView" android:src="@drawable/abc"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:theme="@style/Base.TextAppearance.AppCompat" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Turn On"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_toStartOf="@+id/imageView"
android:layout_toLeftOf="@+id/imageView"
android:clickable="true" android:onClick="on" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Get visible"
android:onClick="visible" android:id="@+id/button2"
android:layout_alignBottom="@+id/button"
android:layout_centerHorizontal="true" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="List devices"
android:onClick="list" android:id="@+id/button3"
android:layout_below="@+id/imageView"
android:layout_toRightOf="@+id/imageView"
android:layout_toEndOf="@+id/imageView" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="turn off"
android:onClick="off" android:id="@+id/button4"
android:layout_below="@+id/button" android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ListView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/listView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="@+id/button" android:layout_alignStart="@+id/button"
android:layout_below="@+id/textView2" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Paired devices:"
android:id="@+id/textView2" android:textColor="#ff34ff06"
android:textSize="25dp" android:layout_below="@+id/button4"
android:layout_alignLeft="@+id/listView"
android:layout_alignStart="@+id/listView" />
</RelativeLayout>
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList; import java.util.Set;
public class MainActivity extends Activity {
Button b1,b2,b3,b4;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button); b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.button3); b4=(Button)findViewById(R.id.button4);
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.listView);
}
public void on(View v)
{
if (!BA.isEnabled())
{
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0); Toast.makeText(getApplicationContext(), "Turned
on",Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
public void off(View v)
{
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
public void visible(View v)
{
Intent getVisible = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void list(View v)
{
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired
Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
}
Animation
• Animation is the process of creating motion and shape change
• It define the properties of our Views that should be animated using
a technique called Tween Animation.It take the following
parameters i.e. size, time duration , rotation angle, start value , end
value, and perform the required animation on that object.You
can execute the animation by specifying transformations on your
View. This can be done in XML resource files or programmatically.
Property Description
alpha Fade in or out
rotation, rotationX, rotationY Spin or flip
scaleX ,scaleY Grow or shrink
x,y,z Position
translationX, translationY,
Offset from Position
translationZ (API 21+)
Drawable Animation:
• This animation allows the user to load drawable resources and
display them one frame after another. This method of animation is
useful when user wants to animate things that are easier to
represent with Drawable resources.
• 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()(this method is used to load animation) of
the class AnimationUtils. We are going to receive the result in an
instance of Animation Object. Its syntax is as follows −
• Animation animation
=AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.myanimation);
• 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.
5.cancel(): This method cancels the animation.
Setting The Animation Listeners
(Optional)
Animation listeners can be set by implementing AnimationListener in
our Activity.
If you will use AnimationListener, then you will have to override
following methods.
onAnimationStart –
@Override public void onAnimationStart(Animation animation) { }
onAnimationEnd –
@Override public void onAnimationEnd(Animation animation) { }
onAnimationRepeat –
@Override public void onAnimationRepeat(Animation animation) { }
• Scale Animation
Scale Animation is used to make a smaller or larger
view either on x axis or y axis. Pivot point can also be
specified around which we want the animation to take
place.
• Rotate Animation
Rotate Animation is used to rotate a view around a
pivot point by a certain number of degrees.
• Translate Animation
Translate Animation is used to move a view along the x
or y axis.
• Alpha Animation
Transparency of a view can be changed by Alpha
Animation
Interpolator:
The dictionary meaning of Interpolate is to alter, intercept or insert in between two
things or events.
It is used to insert or apply an additional animation effects between the start and the
end value of the property of an object.It is also used to define the rate of change
of an animation.
Types of Interpolator:
1.Linear Interpolator: It is the default interpolator of all animations. It defines that the
rate of the change of the animation is constant.
2.Accelerate Interpolator: Accelerates the moving of the view, it starts out slowly and
then accelerates until it reaches the final position.
3.Decelerate Interpolator: Does the opposite of the accelerate interpolator. It starts
out fast and the slows down.
4.Accelerate Decelerate Interpolator: Makes the moving go slow at the beginning and
the end, but fast in the middle.
5.Anticipate Interpolator: Moves the animation backwards before it starts
6.Overshoot Interpolator: Does the opposite of the anticipate interpolator. It make
the animation to go further than the defined destintion, and then get back to the
defined destination.
7.Anticipate Overshoot Interpolator: Combines the anticipate and the overshoot
interpoplator. The change starts backward then flings forward and overshoots the
target value and finally goes back to the final value.
8.Bounce Interpolator: Makes an bounce animation before the desired animation
ends.
9.Cycle Interpolator: Repeats the animation for a specified number of cycles.
Important XML Animation Attributes In Android:
1. android:duration: The duration in which animation is completed is referred to as
duration attribute. It refers to the ideal duration to show the transition on the
screen.
android:duration="1500“
2. android:fillAfter: This attribute defines whether the view should be visible or not
at the end of the animation.We have set its value true in our animation. If it
would set to false then element changes comes to its previous state after the
animation.
android:fillAfter="true“
3. android:interpolator: This property refers to the rate of change in animation. You
can define your own interpolators using the time as the constraint. In this
animation we have used an inbuilt interpolator i.e. linear interpolator.
android:interpolator="@android:anim/linear_interpolator"
4. android:startOffset: It refers to the waiting time before an animation starts.
android:startOffset="2000“
5. android:repeatMode: When user wants the animation to be repeated then this
attribute is used
android:repeatMode="restart“
6. android:repeatCount: This attribute defines the number of repetitions on
animation.
android:repeatCount="infinite"
Setting the Animation Listeners
• By default, our application code runs in our main thread and every
statement is therefore execute in a sequence.
• If we need to perform long tasks/operations then our main thread
is blocked until the corresponding operation has finished.
• For providing a good user experience in our application we need to
use AsyncTasks class that runs in a separate thread.
• This class will executes everything in doInBackground() method
inside of other thread which doesn’t have access to the GUI where
all the views are present.
• The onPostExecute() method of this class synchronizes itself again
with the main UI thread and allows it to make some updating.
• This method is called automatically after the doInBackground
method finished its work.
AsyncTask’s three parameters
editor.clear();
editor.commit(); // commit changes
<?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/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="UserName" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:inputType="textPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Login" />
</LinearLayout>
details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr
oid"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_gravity="center"
android:layout_marginTop="170dp"
android:textSize="20dp"/>
<Button
android:id="@+id/btnLogOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Log Out" />
</LinearLayout>
MainActivity.java
package com.tutlane.sharedpreferencesexample;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button loginBtn;
SharedPreferences pref;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
loginBtn = (Button)findViewById(R.id.btnLogin);
pref = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(MainActivity.this,DetailsActivity.class);
if(pref.contains("username") && pref.contains("password")){
startActivity(intent);
}
loginBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString();
String password = pwd.getText().toString();
if(username.equals("suresh") && password.equals("dasari")){
SharedPreferences.Editor editor = pref.edit();
editor.putString("username",username);
editor.putString("password",password);
editor.commit();
Toast.makeText(getApplicationContext(), "Login
Successful",Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else
{
Toast.makeText(getApplicationContext(),"Credentials are not
valid",Toast.LENGTH_SHORT).show();
}
}
});
}
}
DetailsActivity.java
package com.tutlane.sharedpreferencesexample;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class DetailsActivity extends AppCompatActivity {
SharedPreferences prf;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button btnLogOut = (Button)findViewById(R.id.btnLogOut);
prf = getSharedPreferences("user_details",MODE_PRIVATE);
intent = new Intent(DetailsActivity.this,MainActivity.class);
result.setText("Hello, "+prf.getString("username",null));
btnLogOut.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = prf.edit();
editor.clear();
editor.commit();
startActivity(intent);
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.sharedpreferencesexample">
<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>
<activity android:name=".DetailsActivity" android:label="Shared Prefe
rences - Details"></activity>
</application>
</manifest>
Internal Storage
• In android, Internal Storage is useful to store the data files
locally on the device’s internal memory
using FileOutputStream object. After storing the data files
in device internal storage, we can read the data file from
device using FileInputStream object.
If you observe above code, we are reading a file from device internal
storage by using FileInputStream object openFileInput method with
file name. We used read() method to read one character at a time
from the file and used close() method to close the stream.
Method Description
getChannel() It returns the unique FileChannel object
associated with this file output stream.
getFD() It returns the file descriptor which is
associated with the stream.
read(byte[] b, int off, int len) It reads len bytes of data from the
specified file input stream into an array of
bytes.
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/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="UserName" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:inputType="textPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Save" /> </LinearLayout>
details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr
oid"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_gravity="center"
android:layout_marginTop="170dp"
android:textSize="20dp"/>
<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Back" />
</LinearLayout>
• MainActivity.java
• package com.tutlane.internalstorageexample;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button saveBtn;
FileOutputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
• uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
saveBtn = (Button)findViewById(R.id.btnSave);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String username = uname.getText().toString()+"\n";
String password = pwd.getText().toString();
try {
fstream = openFileOutput("user_details",
Context.MODE_PRIVATE);
fstream.write(username.getBytes());
fstream.write(password.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), "Details Saved
Successfully",Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this,DetailsActivity.class);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
• DetailsActivity.java
• package com.tutlane.internalstorageexample;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class DetailsActivity extends AppCompatActivity {
FileInputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button back = (Button)findViewById(R.id.btnBack);
try {
fstream = openFileInput("user_details");
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
• fstream.close();
String details[] = sbuffer.toString().split("\n");
result.setText("Name: "+ details[0]+"\nPassword:
"+details[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(DetailsActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
• AndroidManifest.xml
• <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.internalstorageexample">
<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>
<activity android:name=".DetailsActivity" android:label="Internal Stor
age - Details"></activity>
</application>
</manifest>
External Storage
• External Storage option to store and retrieve the data from
external storage media such as SD card.
• To read or write files on the external storage, our app must acquire
the WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE s
ystem permissions. For that, we need to add following permissions
in android manifest file like as shown below.
<manifest>
....
<uses-permission android:name="android.permission.WRITE_EXT
ERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXT
ERNAL_STORAGE"/>
....
</manifest>
Checking External Storage Availability
• Before we do any work with external storage, first we need to check whether
the media is available or not by calling getExternalStorageState(). The media
might be mounted to a computer, missing, read-only or in some other state.
To get the media status, we need to write the code like as shown below.
• In case, if we are handling the files that are not intended for other
apps to use, then we should use a private storage directory on the
external storage by calling getExternalFilesDir().
Write a File to External Storage
• By using android FileOutputStream object
and getExternalStoragePublicDirectory method, we can easily create
and write a data to the file in external storage public folders.
If you observe above code, we are reading a file from device Downloads folder
storage by
using FileInputStream object getExternalStoragePublicDirectory method with file
name. We used read() method to read one character at a time from the file and
used close() method to close the stream.
• 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/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="UserName" />
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/txtPwd"
android:inputType="textPassword"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Save" /></LinearLayout>
• details.xml
• <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/andr
oid"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_gravity="center"
android:layout_marginTop="170dp"
android:textSize="20dp"/>
<Button
android:id="@+id/btnBack"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Back" />
</LinearLayout>
• MainActivity.java
• package com.tutlane.externalstorageexample;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
EditText uname, pwd;
Button saveBtn;
FileOutputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uname = (EditText)findViewById(R.id.txtName);
pwd = (EditText)findViewById(R.id.txtPwd);
saveBtn = (Button)findViewById(R.id.btnSave);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
• public void onClick(View v) {
String username = uname.getText().toString()+"\n";
String password = pwd.getText().toString();
try {
ActivityCompat.requestPermissions(MainActivity.this, new Stri
ng[]{android.Manifest.permission.READ_EXTERNAL_STORAGE},23);
File folder =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_
DOWNLOADS);
File myFile = new File(folder,"user_details");
fstream = new FileOutputStream(myFile);
fstream.write(username.getBytes());
fstream.write(password.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), "Details Saved in
"+myFile.getAbsolutePath(),Toast.LENGTH_SHORT).show();
intent = new Intent(MainActivity.this,DetailsActivity.class);
startActivity(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
• DetailsActivity.java
• package com.tutlane.externalstorageexample;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class DetailsActivity extends AppCompatActivity {
FileInputStream fstream;
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.details);
TextView result = (TextView)findViewById(R.id.resultView);
Button back = (Button)findViewById(R.id.btnBack);
try {
File folder = Environment.getExternalStoragePublicDirectory(Environm
ent.DIRECTORY_DOWNLOADS);
• File myFile = new File(folder,"user_details");
fstream = new FileInputStream(myFile);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
sbuffer.append((char)i);
}
fstream.close();
String details[] = sbuffer.toString().split("\n");
result.setText("Name: "+ details[0]+"\nPassword: "+details[1]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intent = new Intent(DetailsActivity.this,MainActivity.class);
startActivity(intent);
}
});
}
}
• AndroidManifest.xml
• <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.externalstorageexample">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORA
GE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAG
E"/>
<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>
<activity android:name=".DetailsActivity" android:label="External Storage - De
tails"></activity>
</application>
</manifest>
Android SQLite Database
• SQLite is an open source light weight relational database
management system (RDBMS) to perform database operations,
such as storing, updating, retrieving data from database.
• Generally, in our android applications Shared Preferences, Internal
Storage and External Storage options are useful to store and
maintain the small amount of data. In case, if we want to deal with
large amount of data, then SQLite database is the preferable option
to store and maintain the data in structured format.