Mobile Application Development Chapter 5: Working with Android Media Player

 
MOBILE APPLICATION
DEVELOPMENT
Chapter 5
 
 
Android Media Player
 
We can play and control the audio files in
android by the help of 
MediaPlayer class
.
Here, we are going to see a simple example to
play the audio file. In the next page, we will
see the example to control the audio playback
like start, stop, pause etc.
MediaPlayer class
The 
android.media.MediaPlayer
 class is used to
control the audio or video files.
 
 
 
Methods of MediaPlayer class
There are many methods of MediaPlayer class.
Some of them are as follows:
 
 
 
 
Activity class
 
Let's write the code of to play the audio file.
Here, we are going to play maine.mp3 file located
inside the sdcard/Music directory.
File: MainActivity.java
package
 com.example.audiomediaplayer1;
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);
        MediaPlayer mp=
new
 MediaPlayer();
        
try
{
            mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here
            mp.prepare();
            mp.start();
        }
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();
            }
        });
    }
}
 
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:
 
Android Video Player
 
 
activity_main.xml
 
<RelativeLayout
 xmlns:androclass="http://schemas.android.co
m/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
>
    
<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"   />
</RelativeLayout>
 
 
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;
public
 
class
 MainActivity 
extends
 Activity {
      MediaRecorder recorder;
      File audiofile = 
null
;
      
static
 
final
 String TAG = "MediaRecording";
      Button startButton,stopButton;
 
 
 @Override
      
public
 
void
 onCreate(Bundle savedInstanceState) {
        
super
.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startButton = (Button) findViewById(R.id.button1);
        stopButton = (Button) findViewById(R.id.button2);     }
      
public
 
void
 startRecording(View view) 
throws
 IOException {
        startButton.setEnabled(
false
);
        stopButton.setEnabled(
true
);     //Creating file
        File dir = Environment.getExternalStorageDirectory();
        
try
 {
          audiofile = File.createTempFile("sound", ".3gp", dir);
        } 
catch
 (IOException e) {
          Log.e(TAG, "external storage access error");
          
return
;
        }   //Creating MediaRecorder and specifying audio source, output format, encoder & output format
        recorder = 
new
 MediaRecorder();
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(audiofile.getAbsolutePath());
        recorder.prepare();
        recorder.start();  }
 
 
public void stopRecording(View view) {
        startButton.setEnabled(true);
        stopButton.setEnabled(false);
            //stopping recorder
        recorder.stop();
        recorder.release();
           //after stopping the recorder, create the sound file and add it to media library.
        addRecordingToMediaLibrary();
      }
      protected void addRecordingToMediaLibrary() {
            //creating content values of size 4
        ContentValues values = new ContentValues(4);
        long current = System.currentTimeMillis();
        values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName());
        values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000));
        values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp");
        values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath());
             //creating content resolver and storing it in the external content uri
        ContentResolver contentResolver = getContentResolver();
        Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Uri newUri = contentResolver.insert(base, values);
           //sending broadcast message to scan the media file so that it can be available
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri));
        Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show();
      }
    }
 
 
 
Android Text To Speech
 
In android, you can convert your text into speech
by the help of 
TextToSpeech
 class. After
completion of the conversion, you can playback
or create the sound file.
Constructor of TextToSpeech class
TextToSpeech(Context
context,TextToSpeech.OnInitListener)
 
Methods of TextToSpeech class
 
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
 
activity_main.xml
 
<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"
    tools:context=".MainActivity" 
>
    
<EditText
    android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="77dp"
        android:layout_marginTop="42dp"
        android:ems="10" 
>
        
<requestFocus
 
/>
   
</EditText>
    
<Button
      android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginLeft="59dp"
        android:layout_marginTop="39dp"
        android:text="Speak" 
/>
    
<TextView
    android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/editText1"
        android:layout_alignBottom="@+id/editText1"
        android:layout_alignParentLeft="true"
        android:text="Enter Text:" 
/>
</RelativeLayout>
 
 
 MainActivity.java
package
 com.example.texttospeech;
 
import
 android.os.Bundle;
import
 android.app.Activity;
import
 android.view.Menu;
import
 java.util.Locale;
import
 android.app.Activity;
import
 android.os.Bundle;
import
 android.speech.tts.TextToSpeech;
import
 android.util.Log;
import
 android.view.View;
import
 android.widget.Button;
import
 android.widget.EditText;
public
 
class
 MainActivity 
extends
 Activity 
implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private
 TextToSpeech tts;
private
 Button buttonSpeak;
private
 EditText editText;
 
 
@Override
public
 
void
 onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = 
new
 TextToSpeech(
this
this
);
buttonSpeak = (Button) findViewById(R.id.button1);
editText = (EditText) findViewById(R.id.editText1);
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:
 
 
The Android sensor framework provided a following classes and interfaces
to access device sensors and acquire raw sensor data.
 
 
Android provides SensorManager and Sensor classes to use the sensors in
our application. In order to use sensors, first thing you need to do is to
instantiate the object of SensorManager class. It can be achieved as follows.
SensorManager sMgr;
sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
 
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 −
 
 
activity_main.xml
(List of sensors supported by mobile)
 
<?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"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<TextView
    android:id="@+id/sensorslist"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="80dp"
    android:text="Sensors"
    android:textSize="20dp"
    android:textStyle="bold"
    android:layout_gravity="center"
    android:visibility="gone"/>
</LinearLayout>
 
MainActivity.java
 
 
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private SensorManager mgr;
    private TextView txtList;   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        txtList = (TextView)findViewById(R.id.sensorslist);
        List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL);
        StringBuilder strBuilder = new StringBuilder();
        for(Sensor s: sensorList){
            strBuilder.append(s.getName()+"\n");
        }     txtList.setVisibility(View.VISIBLE);
        txtList.setText(strBuilder);   }  }
 
Changed background color
when device is shuffled
 activity_main.xml
 
<RelativeLayout
 xmlns:android="http://schemas.android.com/apk/res/androi
d"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" 
>
   
<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;
public
 
class
 MainActivity 
extends
 Activity 
implements
 SensorEventList
ener{
    
private
 SensorManager sensorManager;
      
private
 
boolean
 isColor = 
false
;
      
private
 View view;
      
private
 
long
 lastUpdate;
 
 
 @Override
      
public
 
void
 onCreate(Bundle savedInstanceState) {
        
super
.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        view = findViewById(R.id.textView);
        view.setBackgroundColor(Color.GREEN);
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        lastUpdate = System.currentTimeMillis();
      }
      //overriding two methods of SensorEventListener
      @Override
      
public
 
void
 onAccuracyChanged(Sensor sensor, 
int
 accuracy) {}
      @Override
      
public
 
void
 onSensorChanged(SensorEvent event) {
        
if
 (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
          getAccelerometer(event);
        }
      }
 
 
 
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);
 
 
 
 
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.
 
 
Using Camera By using Camera Api
 
This class is used for controlling device cameras. It can
be used to take pictures when you are building a
camera application.
Camera API works in following ways:
1.
Camera Manager
: This is used to get all the cameras
available in the device like front camera back camera
each having the camera id.
2.
CameraDevice
: You can get it from Camera Manager
class by its id.
3.
CaptureRequest
: You can create a capture request from
camera device to capture images.
4.
CameraCaptureSession
: To get capture request’s from
Camera Device create a CameraCaptureSession.
5.
CameraCaptureSession.CaptureCallback
: This is going
to provide the Capture session results.
 
 
 
Checking Camera Permissions:
 
For the first we have used the Function
requestPermissions(new
String[]{Manifest.permission.CAMERA},MY_CAMERA_PERMIS
SION_CODE);
 
We will check whether the user has given permissions or
not if not then first we will ask the user for permissions if a
user is using Android version above Android Marshmallow(API
23) because From Android Marshmallow(API 23) and above by
default all dangerous permission disabled. When the App
opens for the first time after installation then you have to
grant permissions. But if the android version is below
Marshmallow then this function won’t be called.
 
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:
private static final int CAMERA_REQUEST = 1888
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
{
 if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
 theImage = (Bitmap) data.getExtras().get("data");
photo=getEncodedString(theImage); setDataToDataBase();
}
 }
 
 
getEncodedString(Bitmap bitmap) Method:
 
Since now I am able to click an image from the camera but that
image is in the form of Bitmap but I want to store it as a string in
the database, so I am going to encode it using
ByteArrayOutputStream Class. This Class holds a copy of data and
forwards it to multiple streams.
 
private String getEncodedString(Bitmap bitmap)
 
{
 
ByteArrayOutputStream os = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100, os);
 
/* or use below if you want 32 bit images
bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);*/
 
byte[] imageArr = os.toByteArray();
 
return Base64.encodeToString(imageArr, Base64.URL_SAFE);
 
}
 
 
setDataToDataBase() Method:
 
Now I am storing data(Image) to a database(here I have used SQLite). Here the
ContentValue class helps to put information inside an object in the form of Key-
Value pairs for columns. To Insert or Update your WritableDatabase The object can
then be passed to an instance of the SQLiteDatabase class.
 
private void setDataToDataBase()
 
{
 
db = databaseHandler.getWritableDatabase(); ContentValues cv = new
ContentValues(); cv.put(databaseHandler.KEY_IMG_URL,photo);
 
 long id = db.insert(databaseHandler.TABLE_NAME, null, cv);
 
 if (id < 0)
 
 {
 
Toast.makeText(getContext(), "Something went wrong. Please try again later...",
Toast.LENGTH_LONG).show();
 
}
 
 else
 
 {
 
Toast.makeText(getContext(), "Add successful", Toast.LENGTH_LONG).show();
 
 }
 
}
 
 
Please add CAMERA permission inside your
AndroidManifest.xml file .
<uses-permission
android:name="android.permission.CAMERA" />
 
 
Eg.camera image inside image view as follow:
 
activity_main.xml
 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
 
android:id="@+id/activity_main" 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="com.android_examples.captureimagecamera_android_examplescom.M
ainActivity"
 
android:orientation="vertical" android:background="#FFF9C4">
 <ImageView  android:layout_width="fill_parent"
android:layout_height="300dp"
android:layout_centerHorizontal="true“
 android:id="@+id/imageView" />
<Button android:text="Click here to capture image using camera"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button" />
</LinearLayout>
 
 
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
 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.ImageView;
 import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
 
Button button ;
 
ImageView imageView ;
 
Intent intent ;
 
public static final int RequestPermissionCode = 1 ;
 
 
@Override
protected void onCreate(Bundle savedInstanceState)
{
 
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
 
button = (Button)findViewById(R.id.button);
 
imageView =(ImageView)findViewById(R.id.imageView);
EnableRuntimePermission(); button.setOnClickListener(new
View.OnClickListener()
 
{
 
@Override
 
public void onClick(View view) {
 
 intent = new
Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
 
startActivityForResult(intent, 7);
 
 }
 
});
 
}
 
 
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
 if (requestCode == 7 && resultCode == RESULT_OK)
 {
 Bitmap bitmap = (Bitmap)data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
}
public void EnableRuntimePermission()
{
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CAMERA))
{
Toast.makeText(MainActivity.this,"CAMERA permission allows us to Access CAMERA
app", Toast.LENGTH_LONG).show();
}
else
 {
ActivityCompat.requestPermissions(MainActivity.this,new String[] {
Manifest.permission.CAMERA}, RequestPermissionCode);
}
 }
 
 
@Override
public void onRequestPermissionsResult(int RC, String per[], int[]
PResult)
 {
switch (RC)
{
case RequestPermissionCode:
 if (PResult.length > 0 && PResult[0] ==
PackageManager.PERMISSION_GRANTED)
 
{
Toast.makeText(MainActivity.this,"Permission Granted, Now your
application can access CAMERA.", Toast.LENGTH_LONG).show();
 
} else
 
{
 
Toast.makeText(MainActivity.this,"Permission Canceled, Now your
application cannot access CAMERA.", Toast.LENGTH_LONG).show(); }
 
break;
 
 }
 }
 }
 
Camera Video Capture And Save On
SDCard
 
XML FILE : AndroidManifest.xml
To access external storage(SDCARD).
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STO
RAGE" />
 
    <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);
                // create a file to save the video
                fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);
                // set the image file name
                intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
                // set the video image quality to high
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                // start the Video Capture Intent
                startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
            }});
    }
 
 
/** Create a file Uri for saving an image or video */
    private static Uri getOutputMediaFileUri(int type){
          return Uri.fromFile(getOutputMediaFile(type));
    }
    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type){
        // Check that the SDCard is mounted
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                  Environment.DIRECTORY_PICTURES), "MyCameraVideo");
        // Create the storage directory(MyCameraVideo) if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                output.setText("Failed to create directory MyCameraVideo.");
                Toast.makeText(ActivityContext, "Failed to create directory MyCameraVideo.",
                        Toast.LENGTH_LONG).show();
                Log.d("MyCameraVideo", "Failed to create directory MyCameraVideo.");
                return null;
            }
        }
 
 
// Create a media file name
        // 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) {
        // After camera screen this code will excuted
        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                output.setText("Video File : " +data.getData());
                // Video captured and saved to fileUri specified in the Intent
                Toast.makeText(this, "Video saved to:" + data.getData(), Toast.LENGTH_LONG).show();
            } else if (resultCode == RESULT_CANCELED) {
                output.setText("User cancelled the video capture.");
                // User cancelled the video capture
                Toast.makeText(this, "User cancelled the video capture.",
                        Toast.LENGTH_LONG).show();
            } else {
                output.setText("Video capture failed.");
                // Video capture failed, advise user
                Toast.makeText(this, "Video capture failed.",
                        Toast.LENGTH_LONG).show();
            }
        }
    }
}
 
Bluetooth
 
Bluetooth is a way to send or receive data
between two different devices. Android platform
includes support for the Bluetooth framework
that allows a device to wirelessly exchange data
with other Bluetooth devices.
Android provides Bluetooth API to perform these
different operations.
Scan for other Bluetooth devices
Get a list of paired devices
Connect to other devices through service discovery
 
Android Bluetooth API
 
The android.bluetooth package provides a lot of interfaces classes to
work with bluetooth such as:
BluetoothAdapter
BluetoothDevice
BluetoothSocket
BluetoothServerSocket
BluetoothClass
BluetoothProfile
BluetoothProfile.ServiceListener
BluetoothHeadset
BluetoothA2dp
BluetoothHealth
BluetoothHealthCallback
BluetoothHealthAppConfiguration
 
BluetoothAdapter class
 
 
By the help of BluetoothAdapter class, we can perform
fundamental tasks such as initiate device discovery, query a
list of paired (bonded) devices, create a
BluetoothServerSocket instance to listen for connection
requests etc.
 
Constants of BluetoothAdapter class
BluetoothAdapter class provides many constants. Some of them
are as follows:
 
String ACTION_REQUEST_ENABLE
String ACTION_REQUEST_DISCOVERABLE
String ACTION_DISCOVERY_STARTED
String ACTION_DISCOVERY_FINISHED
 
 
Methods of BluetoothAdapter class
 
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.
 
In case, if we want to discover the available Bluetooth
devices or manipulate Bluetooth settings from our app,
we need to define 
BLUETOOTH_ADMIN
 permission.
 
 
<manifest ... >
<uses-
permission android:name="android.permission.BLUET
OOTH"/>
<uses-
permission android:name="android.permission.BLUET
OOTH_ADMIN"/>
<uses-
permission android:name="android.permission.ACCESS
_COARSE_LOCATION"/>
...
</manifest>
 
Android BluetoothAdapter Class
 
In android, we can perform Bluetooth related activities by using 
BluetoothAdapter
 class in our
applications.
By using 
BluetoothAdapter
 object, we can interact with device’s Bluetooth adapter to perform
Bluetooth related operations. In case, if device does not contain any Bluetooth adapter, then it will
return null.
Following is the code snippet to initialize 
BluetoothAdapter
 class and to know whether the Bluetooth is
supported on the device or not.
 
BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
if(bAdapter==null)
{
    // Device won't support Bluetooth
}
 
If you observe above code snippet, we used 
getDefaultAdapter()
 method of 
BluetoothAdapter
 class,
which will return whether the device contains Bluetooth adapter 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.
Following is the code snippet to enable a Bluetooth by
using 
BluetoothAdapter
 parameter 
ACTION_REQUEST_ENABLE
.
if(!bAdapter.isEnabled())
{
    Intent eintent = new Intent(BluetoothAdapter.ACTION_REQUEST_
ENABLE);
    startActivityForResult(eintent, intVal);
}
If you observe above code snippet, we used 
startActivityForResult()
 method
with 
ACTION_REQUEST_ENABLE
  
intent
 action parameter to enable a
Bluetooth.
The second parameter 
intVal
 in 
startActivityForResult()
 method is a locally
defined integer that must be greater than 
0
 and the system will return this
parameter back to us during 
onActivityResult()
 implementation as
requestCode
 parameter.
 
Android Enable Discoverability
 
To make the device discoverable to other devices, we need to start the
new 
activity
 by calling 
startActivityForResult(intent, int)
 with
the  
ACTION_REQUEST_DISCOVERABLE
 
intent
.
Following is the code snippet to enable the system’s discoverable mode to make
sure that the device discoverable to other devices.
Intent dIntent =  new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(dIntent);
 
If you observe above code snippet, we are making sure our device discoverable to
other devices using 
ACTION_REQUEST_DISCOVERABLE
. By default, the device
becomes discoverable for 120 seconds. We can extend the device discoverable
duration up to 3600 seconds (1 hour), by adding
the 
EXTRA_DISCOVERABLE_DURATION
 extra.
 
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.
// Get paired devices.
Set<BluetoothDevice> pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
    // There are paired devices. Get the name and address of each paired d
evice.
    for (BluetoothDevice device : pairedDevices) {
        String deviceName = device.getName();
        String deviceHardwareAddress = device.getAddress(); // MAC address
    }
}
 
If you observe above code, we are getting the Bluetooth paired devices name
and mac address by using 
BluetoothDevice
 object.
 
 
<?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.
 
Android View animation can make animation on any View objects,
such as ImageView, TextView or Button objects. View animation can
only animate simple properties like position, size, rotation, and the
alpha property that allows you animate the transparency of a View.
 
The drawback of this mechanism is that it can only be applied to
Views.
 
Property Animation:
 
This animation was introduced in Android 3.0 (API level 11). It
allows the user to animate anything.
Property animations are highly customizable, you can specify the
duration, the number of repeats, the type of interpolation, and
the frame rate of the animation. The Property Animation system
is always preferred for more complex animations.
Property animations allow us to animate any property of any
object from one value to another over a specified duration.
 
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
 
This is only needed if we wish to listen to events
like start, end or repeat. For this the activity must
implement 
AnimationListener
 and the following
methods need to overridden.
onAnimationStart
 : This will be triggered once
the animation started
onAnimationEnd
 : This will be triggered once the
animation is over
onAnimationRepeat
 : This will be triggered if the
animation repeats
 
Fade In Animation
fade_in.xml
 
    <set
xmlns:android="https://schemas.android.com
/apk/res/android" android:fillAfter="true" >
<alpha android:duration="1000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/acceler
ate_interpolator" android:toAlpha="1.0" />
</set>
 
Here 
alpha
 references the opacity of an object. An object with lower alpha values
is more transparent, while an object with higher alpha values is less transparent,
more opaque. Fade in animation is nothing but increasing alpha value from 0 to 1.
 
Fade Out Animation
fade_out.xml
 
<set
xmlns:android="https://schemas.android.com
/apk/res/android" android:fillAfter="true" >
<alpha android:duration="1000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/acceler
ate_interpolator" android:toAlpha="0.0" />
</set>
 
Fade out android animation is exactly opposite to fade in, where we need to decrease
the alpha value from 1 to 0.
 
Blink Animation
blink.xml
 
<set
xmlns:android="https://schemas.android.com/ap
k/res/android"> <alpha android:fromAlpha="0.0"
android:toAlpha="1.0"
android:interpolator="@android:anim/accelerate
_interpolator" android:duration="600"
android:repeatMode="reverse"
android:repeatCount="infinite"/> </set>
 
 
Here fade in and fade out are performed infinitely
in reverse mode each time.
 
Zoom In Animation
zoom_in.xml
 
<set
xmlns:android="https://schemas.android.com/ap
k/res/android" android:fillAfter="true" > <scale
xmlns:android="https://schemas.android.com/ap
k/res/android" android:duration="1000"
android:fromXScale="1" android:fromYScale="1"
android:pivotX="50%" android:pivotY="50%"
android:toXScale="3" android:toYScale="3" >
</scale> </set>
 
 
We use pivotX="50%" and pivotY="50%" to perform
zoom from the center of the element.
 
Zoom Out Animation
zoom_out.xml
 
<set
xmlns:android="https://schemas.android.com/ap
k/res/android" android:fillAfter="true" > <scale
xmlns:android="https://schemas.android.com/ap
k/res/android" android:duration="1000"
android:fromXScale="1.0"
android:fromYScale="1.0" android:pivotX="50%"
android:pivotY="50%" android:toXScale="0.5"
android:toYScale="0.5" > </scale> </set>
 
Rotate Animation
rotate.xml
 
<set
xmlns:android="https://schemas.android.com/apk/res
/android"> <rotate android:fromDegrees="0"
android:toDegrees="360" android:pivotX="50%"
android:pivotY="50%" android:duration="600"
android:repeatMode="restart"
android:repeatCount="infinite"
android:interpolator="@android:anim/cycle_interpolat
or"/> </set>
from/toDegrees
 tag is used here to specify the degrees
and a cyclic interpolator is used.
 
Move Animation
move.xml
 
<set
xmlns:android="https://schemas.android.com
/apk/res/android"
android:interpolator="@android:anim/linear_
interpolator" android:fillAfter="true">
<translate android:fromXDelta="0%p"
android:toXDelta="75%p"
android:duration="800" /> </set>
 
Slide Up Animation
slide_up.xml
 
<set
xmlns:android="https://schemas.android.com/apk/res
/android" android:fillAfter="true" > <scale
android:duration="500" android:fromXScale="1.0"
android:fromYScale="1.0"
android:interpolator="@android:anim/linear_interpola
tor" android:toXScale="1.0" android:toYScale="0.0" />
</set>
It’s achieved by
setting 
android:fromYScale=”1.0″
 and 
android:toYScal
e=”0.0″
 inside the 
scale
 tag.
 
Slide Down Animation
slide_down.xml
 
<set
xmlns:android="https://schemas.android.com
/apk/res/android" android:fillAfter="true">
<scale android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" /> </set>
 
Bounce Animation
bounce.xml
 
<set
xmlns:android="https://schemas.android.com
/apk/res/android" android:fillAfter="true"
android:interpolator="@android:anim/bounc
e_interpolator"> <scale
android:duration="500"
android:fromXScale="1.0"
android:fromYScale="0.0"
android:toXScale="1.0"
android:toYScale="1.0" /> </set>
 
Sequential Animation
sequential.xml
 
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >
 <!-- Move --> <translate android:duration="800" android:fillAfter="true"
android:fromXDelta="0%p" android:startOffset="300" android:toXDelta="75%p"
/> <translate android:duration="800" android:fillAfter="true"
android:fromYDelta="0%p" android:startOffset="1100" android:toYDelta="70%p"
/>
 <translate android:duration="800" android:fillAfter="true"
android:fromXDelta="0%p" android:startOffset="1900" android:toXDelta="-75%p"
/>
 <translate android:duration="800" android:fillAfter="true"
android:fromYDelta="0%p" android:startOffset="2700" android:toYDelta="-70%p"
/>
 <!-- Rotate 360 degrees --> <rotate android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/cycle_interpolator" android:pivotX="50%"
android:pivotY="50%" android:startOffset="3800" android:repeatCount="infinite"
android:repeatMode="restart" android:toDegrees="360" />
 </set>
 
Together Animation
together.xml
 
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:fillAfter="true"
android:interpolator="@android:anim/linear_interpolator" >
<!-- Move -->
<scale xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="4000" android:fromXScale="1"
android:fromYScale="1" android:pivotX="50%"
android:pivotY="50%" android:toXScale="4" android:toYScale="4" >
</scale>
<!-- Rotate 180 degrees -->
<rotate android:duration="500" android:fromDegrees="0"
android:pivotX="50%" android:pivotY="50%"
android:repeatCount="infinite" android:repeatMode="restart"
android:toDegrees="360" />
 </set>
 
activity_main.xml
 
 
<ScrollView xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent" >
<RelativeLayout android:layout_width="match_parent"
android:layout_height="match_parent">
<Button android:id="@+id/btnFadeIn" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:text="Fade In" />
 <TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Fade In" android:id="@+id/txt_fade_in"
android:layout_alignBottom="@+id/btnFadeIn"
android:layout_alignLeft="@+id/txt_fade_out"
android:layout_alignStart="@+id/txt_fade_out" />
<Button android:id="@+id/btnFadeOut" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnFadeIn" android:text="Fade Out" />
 <Button android:id="@+id/btnCrossFade" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnFadeOut" android:text="Cross Fade" />
 
 
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Cross Fade In" android:id="@+id/txt_out"
android:visibility="gone" android:layout_gravity="center_horizontal"
android:layout_alignTop="@+id/txt_in"
android:layout_alignLeft="@+id/txt_in"
android:layout_alignStart="@+id/txt_in" /> <Button
android:id="@+id/btnBlink" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnCrossFade" android:text="Blink" />
<Button android:id="@+id/btnZoomIn"
android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnBlink" android:text="Zoom In" />
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Blink" android:id="@+id/txt_blink"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/btnBlink"
android:layout_alignLeft="@+id/txt_zoom_in"
android:layout_alignStart="@+id/txt_zoom_in" />
 
 
<Button android:id="@+id/btnZoomOut" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnZoomIn" android:text="Zoom Out" /> <Button
android:id="@+id/btnRotate" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnZoomOut" android:text="Rotate" /> <Button
android:id="@+id/btnMove" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnRotate" android:text="Move" /> <Button
android:id="@+id/btnSlideUp" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnMove" android:text="Slide Up" /> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Fade Out" android:id="@+id/txt_fade_out"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/btnFadeOut"
android:layout_alignLeft="@+id/txt_in" android:layout_alignStart="@+id/txt_in"
/>
 
 
<Button android:id="@+id/btnSlideDown" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnSlideUp" android:text="Slide Down" /> <Button
android:id="@+id/btnBounce" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnSlideDown" android:text="Bounce" /> <Button
android:id="@+id/btnSequential" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_margin="5dp"
android:layout_below="@id/btnBounce" android:text="Sequential Animation" />
<Button android:id="@+id/btnTogether" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btnSequential" android:layout_margin="5dp"
android:text="Together Animation" /> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Cross Fade Out" android:id="@+id/txt_in"
android:layout_gravity="center_horizontal"
android:layout_alignBottom="@+id/btnCrossFade"
android:layout_alignLeft="@+id/txt_blink"
android:layout_alignStart="@+id/txt_blink" />
 
 
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" android:text="Zoom In"
android:id="@+id/txt_zoom_in" android:layout_alignBottom="@+id/btnZoomIn"
android:layout_alignLeft="@+id/txt_zoom_out" android:layout_alignStart="@+id/txt_zoom_out"
/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" android:text="Zoom Out"
android:id="@+id/txt_zoom_out" android:layout_alignBottom="@+id/btnZoomOut"
android:layout_toRightOf="@+id/btnSequential" android:layout_toEndOf="@+id/btnSequential"
/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" android:text="Rotate"
android:id="@+id/txt_rotate" android:layout_above="@+id/btnMove"
android:layout_toRightOf="@+id/btnSequential" android:layout_toEndOf="@+id/btnSequential"
/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" android:text="Move"
android:id="@+id/txt_move" android:layout_alignBottom="@+id/btnMove"
android:layout_alignLeft="@+id/txt_slide_up" android:layout_alignStart="@+id/txt_slide_up" />
<TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium" android:text="Slide Up"
android:id="@+id/txt_slide_up" android:layout_alignBottom="@+id/btnSlideUp"
android:layout_toRightOf="@+id/btnSequential" android:layout_toEndOf="@+id/btnSequential"
/>
 
 
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Slide Down" android:id="@+id/txt_slide_down"
android:layout_alignBottom="@+id/btnSlideDown"
android:layout_alignLeft="@+id/txt_slide_up"
android:layout_alignStart="@+id/txt_slide_up" /> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Bounce" android:id="@+id/txt_bounce"
android:layout_alignBottom="@+id/btnBounce"
android:layout_alignLeft="@+id/txt_slide_down"
android:layout_alignStart="@+id/txt_slide_down" /> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Sequential" android:id="@+id/txt_seq"
android:layout_alignBottom="@+id/btnSequential"
android:layout_alignLeft="@+id/txt_bounce"
android:layout_alignStart="@+id/txt_bounce" /> <TextView
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Together" android:id="@+id/txt_tog"
android:layout_alignBottom="@+id/btnTogether"
android:layout_toRightOf="@+id/btnSequential"
android:layout_toEndOf="@+id/btnSequential" /> </RelativeLayout>
</ScrollView>
 
 
import android.app.Activity; import android.content.Intent; import
android.os.Bundle; import android.view.View; import
android.view.animation.Animation; import
android.view.animation.AnimationUtils; import
android.widget.Button; import android.widget.TextView; public
class MainActivity extends Activity { Button btnFadeIn, btnFadeOut,
btnCrossFade, btnBlink, btnZoomIn, btnZoomOut, btnRotate,
btnMove, btnSlideUp, btnSlideDown, btnBounce, btnSequential,
btnTogether; Animation
animFadeIn,animFadeOut,animBlink,animZoomIn,animZoomOut,an
imRotate
,animMove,animSlideUp,animSlideDown,animBounce,animSequent
ial,animTogether,animCrossFadeIn,animCrossFadeOut; TextView
txtFadeIn,txtFadeOut,txtBlink,txtZoomIn,txtZoomOut,txtRotate,txt
Move,txtSlideUp,
txtSlideDown,txtBounce,txtSeq,txtTog,txtIn,txtOut; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
 
 
btnFadeIn = (Button) findViewById(R.id.btnFadeIn); btnFadeOut = (Button)
findViewById(R.id.btnFadeOut); btnCrossFade = (Button)
findViewById(R.id.btnCrossFade); btnBlink = (Button) findViewById(R.id.btnBlink);
btnZoomIn = (Button) findViewById(R.id.btnZoomIn); btnZoomOut = (Button)
findViewById(R.id.btnZoomOut); btnRotate = (Button)
findViewById(R.id.btnRotate); btnMove = (Button) findViewById(R.id.btnMove);
btnSlideUp = (Button) findViewById(R.id.btnSlideUp); btnSlideDown = (Button)
findViewById(R.id.btnSlideDown); btnBounce = (Button)
findViewById(R.id.btnBounce); btnSequential = (Button)
findViewById(R.id.btnSequential); btnTogether = (Button)
findViewById(R.id.btnTogether);
txtFadeIn=(TextView)findViewById(R.id.txt_fade_in);
txtFadeOut=(TextView)findViewById(R.id.txt_fade_out);
txtBlink=(TextView)findViewById(R.id.txt_blink);
txtZoomIn=(TextView)findViewById(R.id.txt_zoom_in);
txtZoomOut=(TextView)findViewById(R.id.txt_zoom_out);
txtRotate=(TextView)findViewById(R.id.txt_rotate);
txtMove=(TextView)findViewById(R.id.txt_move);
txtSlideUp=(TextView)findViewById(R.id.txt_slide_up);
txtSlideDown=(TextView)findViewById(R.id.txt_slide_down);
txtBounce=(TextView)findViewById(R.id.txt_bounce);
txtSeq=(TextView)findViewById(R.id.txt_seq);
txtTog=(TextView)findViewById(R.id.txt_tog);
txtIn=(TextView)findViewById(R.id.txt_in);
txtOut=(TextView)findViewById(R.id.txt_out);
 
 
animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in); animFadeIn =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_in);
// fade in btnFadeIn.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
txtFadeIn.setVisibility(View.VISIBLE);
txtFadeIn.startAnimation(animFadeIn); } }); animFadeOut =
AnimationUtils.loadAnimation(getApplicationContext(), R.anim.fade_out);
// fade out btnFadeOut.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
txtFadeOut.setVisibility(View.VISIBLE);
txtFadeOut.startAnimation(animFadeOut); } });
animCrossFadeIn = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_in);
animCrossFadeOut = AnimationUtils.loadAnimation(getApplicationContext(),
R.anim.fade_out);
// cross fade btnCrossFade.setOnClickListener(new View.OnClickListener() {
@Override
 
 
public void onClick(View v) {
txtOut.setVisibility(View.VISIBLE);
 // start fade in animation
txtOut.startAnimation(animCrossFadeIn);
// start fade out animation
txtIn.startAnimation(animCrossFadeOut);
} });
animBlink = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.blink);
// blink btnBlink.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v) {
txtBlink.setVisibility(View.VISIBLE);
txtBlink.startAnimation(animBlink); } });
animZoomIn = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_in); // Zoom In btnZoomIn.setOnClickListener(new
View.OnClickListener() {
 @Override
public void onClick(View v) {
txtZoomIn.setVisibility(View.VISIBLE);
txtZoomIn.startAnimation(animZoomIn);
} });
animZoomOut = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.zoom_out); // Zoom Out
btnZoomOut.setOnClickListener(new View.OnClickListener()
{ @Override public void onClick(View v)
{txtZoomOut.setVisibility(View.VISIBLE);
txtZoomOut.startAnimation(animZoomOut);
} }); animRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
// Rotate btnRotate.setOnClickListener(new View.OnClickListener() {
 
 
 @Override
public void onClick(View v) {
txtRotate.startAnimation(animRotate); } });
animMove = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.move);
// Move
btnMove.setOnClickListener(new View.OnClickListener()
{
 @Override
public void onClick(View v) {
 txtMove.startAnimation(animMove);
 } });
animSlideUp = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_up);
// Slide Up btnSlideUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
txtSlideUp.startAnimation(animSlideUp);
} });
animSlideDown = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.slide_down);
// Slide Down
btnSlideDown.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
txtSlideDown.startAnimation(animSlideDown);
} });
 
 
animBounce = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
// Slide Down btnBounce.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
txtBounce.startAnimation(animBounce);
} });
animSequential = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.sequential);
// Sequential
btnSequential.setOnClickListener(new View.OnClickListener() {
@Override
 public void onClick(View v) {
txtSeq.startAnimation(animSequential);
 } });
animTogether = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.together);
 // Together
btnTogether.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) { txtTog.startAnimation(animTogether); } }); } }
 
 
 
A sync Task
 
Android UI Main Thread
Android handles input events/tasks with a single User
Interface (UI) thread and the thread is called Main
thread. Main thread cannot handle concurrent
operations as it handles only one event/operation at a
time.
Concurrent Processing in Android
If input events or tasks are not handled concurrently,
whole code of an Android application runs in the main
thread and each line of code is executed one after
each other.
 
 
Assume if you perform a long lasting operation, for example
accessing resource (like MP3, JSON, Image) from the
Internet, the application goes hung state until the
corresponding operation is finished.
To bring good user experience in Android applications, all
potentially slow running operations or tasks in an Android
application should be made to run asynchronously.
Here are some examples for slow running tasks
Accessing resources (like MP3, JSON, Image) from Internet
Database operations
Webservice calls
Complex logic that takes quite long time
 
What is AsyncTask?
 
AsyncTask is an abstract Android class which helps the
Android applications to handle the Main UI thread in
efficient way. AsyncTask class allows us to perform long
lasting tasks/background operations and show the result on
the UI thread without affecting the main thread.
 
 
Android application runs on a single thread when launched.
Due to this single thread model tasks that take longer time
to fetch the response can make the application non-
responsive. To avoid this we use android AsyncTask to
perform the heavy tasks in background on a dedicated
thread and passing the results back to the UI thread. Hence
use of AsyncTask in android application keeps the UI thread
responsive at all times.
 
Need of AsyncTask In Android
 
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
 
android.os.AsyncTask<Params, Progress, Result>
Where,
1. Params — the type of the parameters sent to the
task upon execution
the type of parameters passed into execute()
2.Progress — the type of the progress units published
during the background computation
3.Result — the type of the result of the background
computation
must be the return type of doInBackground
 
Syntax of AsyncTask In Android
 
Create a new class inside Activity class and subclass it by extending AsyncTask
 
private class Demo extends AsyncTask<URL, Integer, Long>
 {
 protected Long doInBackground(URL... urls)
 {
     //Yet to code
}
 protected void onProgressUpdate(Integer... progress)
 {
     //Yet to code
     }
 protected void onPostExecute(Long result)
 {
   //Yet to code
  }
}
 
 
Execute the task simply by invoking execute
method
new Demo().execute(url1, url2, url3);
 
Methods of AsyncTask
 
 
 
execute(Params… params)
 : This method is invoked in java code to start the
asynchronous task.
 
void onPreExecute()
 :  Used to do some UI operation before performing
background tasks.
 
String doInBackground(Integer… inputParams)
 : Run immediately
after 
onPreExecute()
 is completed, it is used to perform more time-consuming
operations. This method accepts the input parameters and returns the calculated
results. During the execution, you can call 
publishProgress(Progress… Values)
 to
update the progress information.
 
void onProgressUpdate(Progress… values) : 
This method will be invoked when
execute 
publishProgress(Progress… Values)
 method in java code. Generally, we
update UI component’s status such as text, progress percentage in this method.
 
void onPostExecute(String result)
 :  When background task complete, this method
will be invoked automatically. Parameter result’s value is just
which 
doInBackground(Params… params)
 method returned.
 
void onCancelled(String result)
 : This method will be invoked when 
AsyncTask’s
cancel(boolean cancel) 
method is invoked.
 
AsyncTask – Rules to be followed
 
The AsyncTask class must be loaded on the UI thread.
The task instance must be created on the UI thread.
Method execute(Params…) must be invoked on the UI
thread.
Should not call onPreExecute(), onPostExecute(Result),
doInBackground(Params…),
onProgressUpdate(Progress…) manually.
The task can be executed only once (an exception will
be thrown if a second execution is attempted.)
 
AndroidManifest.xml
 
<?xml version="1.0" encoding="utf-8"?> <manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.legendblogs.asynctask"> <application android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:supportsRtl="true" android:theme="@style/AppTheme"> <activity
android:name=".MainActivity"> <intent-filter> <action
android:name="android.intent.action.MAIN" /> <category
android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application> </manifest><?xml version="1.0" encoding="utf-8"?> <manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.legendblogs.asynctask"> <application android:allowBackup="true"
android:icon="@mipmap/ic_launcher" android:label="@string/app_name"
android:supportsRtl="true" android:theme="@style/AppTheme"> <activity
android:name=".MainActivity"> <intent-filter> <action
android:name="android.intent.action.MAIN" /> <category
android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity>
</application> </manifest>
 
activity_main.xml
 
<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" 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="com.legendblogs.asynctask.MainActivity">
 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Welcome to Legend Blogs Exmpale" android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" android:textStyle="bold" android:textSize="20dp"
android:id="@+id/textView2" />
 <TextView android:layout_width="wrap_content" android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" android:text="Please enter a waiting
Time" android:id="@+id/textView" android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" android:layout_marginTop="64dp" />
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content"
android:id="@+id/editText" android:layout_below="@+id/textView" android:layout_marginTop="56dp"
android:layout_alignEnd="@+id/textView" android:layout_alignStart="@+id/textView" />
<Button android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Run AsyncTask" android:id="@+id/button" android:layout_below="@+id/editText"
android:layout_centerHorizontal="true" android:layout_marginTop="62dp" /> </RelativeLayout>
 
MainActivity.java
 
package com.legendblogs.asynctask;
 import android.content.Context; import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
 import android.view.View;
 import android.widget.Button;
 import android.widget.EditText;
 public class MainActivity extends AppCompatActivity {
Context context;
 EditText editText;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState)
 {
super.onCreate(savedInstanceState); setContentView(R.layout.activity_main);
this.context = this;
 editText = (EditText) findViewById(R.id.editText);
 button = (Button) findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() {
@Override
 public void onClick(View v) {
if(editText != null && editText.length() > 0)
 new MyAsyncTask(context).execute(editText.getText().toString());
 } }); } }
 
MyAsyncTask.java
 
package com.legendblogs.asynctask; import android.app.ProgressDialog;
import android.content.Context; import android.os.AsyncTask; import
android.util.Log;
public class MyAsyncTask extends AsyncTask<String, String, String>
 {
Context context;
String result;
ProgressDialog progressDialog;
 public MyAsyncTask (Context context)
 {
this.context = context;
 }
@Override
 protected void onPreExecute()
 {
super.onPreExecute();
 progressDialog = ProgressDialog.show(context, "Progress Dialog", null);
}
 
 
@Override
protected String doInBackground(String... args)
 {
 int value = Integer.parseInt(args[0]);
for(int i = 0; i <= value ;i++)
{ try
 {
Thread.sleep(1000);
 } catch (Exception e)
{
Log.v("Error: ", e.toString());
 }
result = "Please wait for " + (value - i ) + " seconds"; publishProgress(result);
}
return null;
}
@Override
 protected void onProgressUpdate(String... text)
 {
progressDialog.setMessage(text[0]);
}
 protected void onPostExecute(String result)
 {
 progressDialog.dismiss();
 } }
 
Shared Preferences
 
 
Shared Preferences
 are used to save and retrieve the primitive data
types (integer, float, Boolean, string, long) data in the form of key-
value pair from a file within an apps file structure.
Generally, the 
Shared Preferences
 object will points to a file that
contains a key-value pairs and provides a simple read and write
methods to save and retrieve the key-value pairs from a file.
The Shared Preferences file is managed by an android framework and
it can be accessed anywhere within the app to read or write data into
the file, but it’s not possible to access the file from any other app so
it’s secured.
The Shared Preferences are useful to store the small collection of
key-values such as user’s login information, app preferences related
to users, etc. to maintain the state of app, next time when they login
again to the app.
 
Handle a Shared Preferences
 
we can save the preferences data either in single or
multiple files based on our requirements.
In case if we use single file to save the preferences, then
we need to use 
getPreferences()
 method to get the
values from Shared Preferences file and for multiple files
we need to call a 
getSharedPreferences()
 method and
pass a file name as a parameter.
 
getSharedPreferences (String PREFS_NAME, int mode)
 
Where
 
PREFS_NAME
 is the name of the file.
mode
 is the operating mode.
Following are the operating modes applicable:
MODE_PRIVATE
: the default mode, where the created file can
only be accessed by the calling application
MODE_WORLD_READABLE
: Creating world-readable files is
very dangerous, and likely to cause security holes in applications
MODE_WORLD_WRITEABLE
: Creating world-writable files is
very dangerous, and likely to cause security holes in applications
MODE_MULTI_PROCESS
: This method will check for
modification of preferences even if the Shared Preference
instance has already been loaded
MODE_APPEND
: This will append the new preferences with the
already existing preferences
MODE_ENABLE_WRITE_AHEAD_LOGGING
: Database open flag.
When it is set, it would enable write ahead logging by default
 
 
Initialization
 
We need an editor to edit and save the changes
in shared preferences. The following code can be
used to get the shared preferences.
 
 
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
// 0 - for private mode Editor
      editor = pref.edit();
 
Storing Data
 
editor.commit()
 is used in order to save changes to
shared preferences.
 
editor.putBoolean("key_name", true); // Storing boolean
true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
 
Retrieving Data
 
Data can be retrieved from saved preferences by
calling 
getString()
 as follows:
 
 
pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
 
Clearing or Deleting Data
 
remove(“key_name”)
 is used to delete that
particular value.
 
 
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
 
clear()
 is used to remove all data
 
 
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.
The data files saved in internal storage is managed by an
android framework and it can be accessed anywhere within
the app to read or write data into the file, but it’s not
possible to access the file from any other app so it’s
secured. When the user uninstall the app, automatically
these data files will be removed from the device internal
storage.
 
Write a File to Internal Storage
 
By using android 
FileOutputStream
 object 
openFileOutput
 method,
we can easily create and write a data to a file in device’s internal
storage.
 
String FILENAME = "user_details";
String name = "suresh";
FileOutputStream fstream = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fstream.write(name.getBytes());
fstream.close();
 
we are creating and writing a file in device internal storage by
using 
FileOutputStream
 object 
openFileOutput
 method with 
file
name
 and 
MODE_PRIVATE
 mode to make the file private to our
application. We used 
write()
 method to write the data in file and
used 
close()
 method to close the stream.
 
In android, we have a different modes such
as 
MODE_APPEND
MODE_WORLD_READBLE
MODE_WORLD_WRIT
EABLE
, etc. to use it in our application based on your requirements.
 
 
Read a File from Internal Storage
 
By using android 
FileInputStream
 object 
openFileInput
 method, we
can easily read the file from device’s internal storage.
 
String FILENAME = "user_details";
FileInputStream fstream = openFileInput(FILENAME);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
    sbuffer.append((char)i);
}
fstream.close();
 
 
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.
 
 
 
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.
 
In android, 
External Storage
 is useful to store the data files
publically on the shared external storage
using 
FileOutputStream
 object. After storing the data files
on external storage, we can read the data file from external
storage media using 
FileInputStream
 object.
 
The data files saved in external storage are word-readable
and can be modified by the user when they enable USB
mass storage to transfer files on a computer.
 
Grant Access to External Storage
 
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.
 
 
boolean Available= false;
boolean Readable= false;
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
    // Both Read and write operations available
    Available= true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){
    // Only Read operation available
    Available= true;
    Readable= true;
} else {
    // SD card not mounted
    Available = false;
}
If you observe above code snippet, we used 
getExternalStorageState()
 method t
o know the status of media mounted to a computer, such as missing, read-o
nly or in some other state.
 
 
In android, by using 
getExternalStoragePublishDirectory()
 method
we can access the files from appropriate public directory by passing
the type of directory we want, such as DIRECTORY_MUSIC,
DIRECTORY_PICTURES, DIRECTORY_RINGTONES, etc. based on our
requirements.
 
If we save our files to corresponding media-type public directory,
the system's media scanner can properly categorize our files in the
system.
following is the example to create a directory for new photo album
in the public pictures directory.
 
// Get the directory for the user's public pictures directory.
File file = new File(Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
    Log.e(LOG_TAG, "Directory not created");
}
 
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.
 
String FILENAME = "user_details";
String name = "suresh";
File folder = Environment.getExternalStoragePublicDirectory(Environ
ment.DIRECTORY_DOWNLOADS);
File myFile = new File(folder, FILENAME);
FileOutputStream fstream = new FileOutputStream(myFile);fstream.
write(name.getBytes());
fstream.close();
 
 
If you observe above code, we are creating and writing a file in
device public 
Downloads
 folder by
using 
getExternalStoragePublicDirectory
 method. We
used 
write()
 method to write the data in file and
used 
close()
 method to close the stream.
 
Read a File from External Storage
 
By using android 
FileInputStream
 object
and 
getExternalStoragePublicDirectory
 method, we can easily read the file from
external storage.
 
String FILENAME = "user_details";
File folder =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWN
LOADS);
File myFile = new File(folder, FILENAME);
FileInputStream fstream = new FileInputStream(myFile);
StringBuffer sbuffer = new StringBuffer();
int i;
while ((i = fstream.read())!= -1){
    sbuffer.append((char)i);
}
fstream.close();
 
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.
 
By default, Android comes with built-in 
SQLite Database
 support so
we don’t need to do any configurations.
Just like we save the files on device’s 
internal storage
, Android
stores our database in a private disk space that’s associated to our
application and the data is secure, because by default this area is
not accessible to other applications.
The package 
android.database.sqlite
 contains all the required API’s
to use SQLite database in our android applications.
 
 
Android SQLite native API is not JDBC, as JDBC
might be too much overhead for a memory-
limited smartphone. Once a database is
created successfully its located
in 
data/data//databases/
 accessible from
Android Device Monitor.
SQLite is a typical 
relational database
,
containing tables (which consists of rows and
columns), indexes etc. We can create our own
tables to hold the data accordingly. This
structure is referred to as a 
schema
.
 
SQLiteOpenHelper
 
class provides the functionality to use the SQLite
database.
The android.database.sqlite.SQLiteOpenHelper
class is used for database creation and version
management. For performing any database
operation, you have to provide the
implementation
of 
onCreate()
 and 
onUpgrade()
 methods of
SQLiteOpenHelper class.
 
Database - Package
 
The main package is android.database.sqlite
that contains the classes to manage your own
databases
 
 
Database - Insertion
 
we can create table or insert data into table using execSQL method defined
in SQLiteDatabase class. Its syntax is given below
mydatabase.execSQL("CREATE TABLE IF NOT EXISTS TutorialsPoint(Username
VARCHAR,Password VARCHAR);"); mydatabase.execSQL("INSERT INTO
Student VALUES('admin','admin');");
 
Database - Fetching
 
We can retrieve anything from database using an
object of the Cursor class. We will call a method
of this class called rawQuery and it will return a
resultset with the cursor pointing to the table.
We can move the cursor forward and retrieve the
data.
Cursor resultSet = mydatbase.rawQuery("Select *
from student",null); resultSet.moveToFirst();
String username = resultSet.getString(0); String
password = resultSet.getString(1);
 
functions available in the Cursor class
 
Methods of SQLiteDatabase class
 
 
Constructors of SQLiteOpenHelper class
 
Methods of SQLiteOpenHelper class
Slide Note
Embed
Share

Explore how to play and control audio files in Android using the MediaPlayer class. Learn about methods available in the MediaPlayer class and see a simple example of playing an audio file. Get insights into setting data sources, playback controls, looping, track selection, volume adjustments, and more. Follow a code example to play an audio file in an Android activity.

  • Android
  • Media Player
  • Audio Control
  • MediaPlayer Class
  • Mobile Development

Uploaded on Sep 15, 2024 | 1 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. MOBILE APPLICATION DEVELOPMENT Chapter 5

  2. Android Media Player We can play and control the audio files in android by the help of MediaPlayer class. Here, we are going to see a simple example to play the audio file. In the next page, we will see the example to control the audio playback like start, stop, pause etc. MediaPlayer class The android.media.MediaPlayer class is used to control the audio or video files.

  3. Methods of MediaPlayer class There are many methods of MediaPlayer class. Some of them are as follows:

  4. Description Method public void setDataSource(String path) sets the data source (file path or http url) to use. public void prepare() prepares the player for playback synchronously. public void start() it starts or resumes the playback. public void stop() it stops the playback. public void pause() it pauses the playback. public boolean isPlaying() checks if media player is playing.

  5. public void seekTo(int millis) seeks to specified time in miliseconds. public void setLooping(boolean looping) sets the player for looping or non- looping. public boolean isLooping() checks if the player is looping or non-looping. public void selectTrack(int index) it selects a track for the specified index. public int getCurrentPosition() returns the current playback position. public int getDuration() returns duration of the file. public void setVolume(float leftVolume,float rightVolume) sets the volume on this player.

  6. Activity class Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file located inside the sdcard/Music directory. File: MainActivity.java package com.example.audiomediaplayer1; 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;

  7. public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MediaPlayer mp=new MediaPlayer(); try{ mp.setDataSource("/sdcard/Music/maine.mp3");//Write your location here mp.prepare(); mp.start(); }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; } }

  8. 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:

  9. 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);

  10. 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(); } });

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

  12. 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:

  13. Method Description public void setMediaController(MediaContro ller controller) sets the media controller to the video view. public void setVideoURI (Uri uri) sets the URI of the video file. public void start() starts the video view. public void stopPlayback() stops the playback. public void pause() pauses the playback. public void suspend() suspends the playback. public void resume() resumes the playback. seeks to specified time in miliseconds. public void seekTo(int millis)

  14. activity_main.xml <RelativeLayout xmlns:androclass="http://schemas.android.co m/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <VideoView android:id="@+id/videoView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_centerVertical="true" /> </RelativeLayout>

  15. 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);

  16. 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; } }

  17. 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.

  18. <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="StopRecording" android:onClick="stopRecording" /> </RelativeLayout>

  19. 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; public class MainActivity extends Activity { MediaRecorder recorder; File audiofile = null; static final String TAG = "MediaRecording"; Button startButton,stopButton;

  20. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); startButton = (Button) findViewById(R.id.button1); stopButton = (Button) findViewById(R.id.button2); public void startRecording(View view) throws IOException { startButton.setEnabled(false); stopButton.setEnabled(true); File dir = Environment.getExternalStorageDirectory(); try { audiofile = File.createTempFile("sound", ".3gp", dir); } catch (IOException e) { Log.e(TAG, "external storage access error"); return; } //Creating MediaRecorder and specifying audio source, output format, encoder & output format recorder = new MediaRecorder(); recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setOutputFile(audiofile.getAbsolutePath()); recorder.prepare(); recorder.start(); } } //Creating file

  21. public void stopRecording(Viewview) { startButton.setEnabled(true); stopButton.setEnabled(false); //stopping recorder recorder.stop(); recorder.release(); //after stopping the recorder,create thesound file and add it to media library. addRecordingToMediaLibrary(); } protectedvoid addRecordingToMediaLibrary() { //creating content values of size 4 ContentValues values = new ContentValues(4); long current = System.currentTimeMillis(); values.put(MediaStore.Audio.Media.TITLE, "audio" + audiofile.getName()); values.put(MediaStore.Audio.Media.DATE_ADDED, (int) (current / 1000)); values.put(MediaStore.Audio.Media.MIME_TYPE, "audio/3gpp"); values.put(MediaStore.Audio.Media.DATA, audiofile.getAbsolutePath()); //creatingcontent resolver and storing it in the external content uri ContentResolvercontentResolver = getContentResolver(); Uri base = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Uri newUri = contentResolver.insert(base,values); //sending broadcastmessage to scan the media file so that it can be available sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, newUri)); Toast.makeText(this, "Added File " + newUri, Toast.LENGTH_LONG).show(); } }

  22. Android Text To Speech In android, you can convert your text into speech by the help of TextToSpeech class. After completion of the conversion, you can playback or create the sound file. Constructor of TextToSpeech class TextToSpeech(Context context,TextToSpeech.OnInitListener)

  23. Methods of TextToSpeech class Method Description int speak (String text, int queueMode, HashMap params) converts the text into speech. 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.

  24. 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 void onInit (int status) Called to signal the completion of the TextToSpeech engine initialization. The status can be SUCCESS or ERROR.

  25. activity_main.xml <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" tools:context=".MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:layout_marginLeft="77dp" android:layout_marginTop="42dp" android:ems="10" > <requestFocus/> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/editText1" android:layout_below="@+id/editText1" android:layout_marginLeft="59dp" android:layout_marginTop="39dp" android:text="Speak" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/editText1" android:layout_alignBottom="@+id/editText1" android:layout_alignParentLeft="true" android:text="Enter Text:" /> </RelativeLayout>

  26. MainActivity.java package com.example.texttospeech; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import java.util.Locale; import android.app.Activity; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; public class MainActivity extends Activity implements TextToSpeech.OnInitListener { /** Called when the activity is first created. */ private TextToSpeech tts; private Button buttonSpeak; private EditText editText;

  27. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tts = new TextToSpeech(this, this); buttonSpeak = (Button) findViewById(R.id.button1); editText = (EditText) findViewById(R.id.editText1); buttonSpeak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { speakOut(); } }); }

  28. @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!"); } }

  29. 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; } }

  30. 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.

  31. 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.

  32. 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. Sensor By using this class we can create an instance of a specific sensor and this class provides a various methods that let you determine the sensor's capabilities. SensorEvent The system uses this class to create a sensor event object and it provides the raw sensor data, type of sensor that generated the event, accuracy of the data, and the timestamp for the event. SensorEventListener We can use this interface to create two callback methods that receive notifications (sensor events) when sensor values change or when sensor accuracy changes.

  33. Android provides SensorManager and Sensor classes to use the sensors in our application. In order to use sensors, first thing you need to do is to instantiate the object of SensorManager class. It can be achieved as follows. SensorManager sMgr; sMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE); 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) { }

  34. 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

  35. 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. 3 registerListener(SensorListener listener, int sensors, int rate) This method registers a listener for the sensor 4 unregisterListener(SensorEventListener listener, Sensor sensor) This method unregisters a listener for the sensors with which it is registered. 5 getOrientation(float[] R, float[] values) This method computes the device's orientation based on the rotation matrix. 6 getAltitude(float p0, float p) This method computes the Altitude in meters from the atmospheric pressure and the pressure at sea level.

  36. activity_main.xml (List of sensors supported by mobile) <?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" android:paddingLeft="10dp" android:paddingRight="10dp"> <TextView android:id="@+id/sensorslist" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="80dp" android:text="Sensors" android:textSize="20dp" android:textStyle="bold" android:layout_gravity="center" android:visibility="gone"/> </LinearLayout>

  37. MainActivity.java import android.hardware.Sensor; import android.hardware.SensorManager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import java.util.List; public class MainActivity extends AppCompatActivity { private SensorManager mgr; private TextView txtList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mgr = (SensorManager)getSystemService(Context.SENSOR_SERVICE); txtList = (TextView)findViewById(R.id.sensorslist); List<Sensor> sensorList = mgr.getSensorList(Sensor.TYPE_ALL); StringBuilder strBuilder = new StringBuilder(); for(Sensor s: sensorList){ strBuilder.append(s.getName()+"\n"); } txtList.setVisibility(View.VISIBLE); txtList.setText(strBuilder); } }

  38. Changed background color when device is shuffled activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi d" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="match_parent" android:text="Shake to switch color" /> </RelativeLayout>

  39. 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; public class MainActivity extends Activity implements SensorEventList ener{ private SensorManager sensorManager; private boolean isColor = false; private View view; private long lastUpdate;

  40. @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); view = findViewById(R.id.textView); view.setBackgroundColor(Color.GREEN); sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); lastUpdate = System.currentTimeMillis(); } //overriding two methods of SensorEventListener @Override public void onAccuracyChanged(Sensor sensor, int accuracy) {} @Override public void onSensorChanged(SensorEvent event) { if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { getAccelerometer(event); } }

  41. 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; } }

  42. @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); } }

  43. 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

  44. 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);

  45. Sr.No Intent type and description ACTION_IMAGE_CAPTURE_SECURE It returns the image captured from the camera , when the device is secured 1 ACTION_VIDEO_CAPTURE It calls the existing video application in android to capture video 2 EXTRA_SCREEN_ORIENTATION It is used to set the orientation of the screen to vertical or landscape 3 EXTRA_FULL_SCREEN It is used to control the user interface of the ViewImage 4 INTENT_ACTION_VIDEO_CAMERA This intent is used to launch the camera in the video mode 5 EXTRA_SIZE_LIMIT It is used to specify the size limit of video or image capture size 6

  46. 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.

  47. Sr.No Activity function description startActivityForResult(Intent intent, int requestCode, Bundle options) It starts an activity , but can take extra bundle of options with it 1 startActivityFromChild(Activity child, Intent intent, int requestCode) It launch the activity when your activity is child of any other activity 2 startActivityFromChild(Activity child, Intent intent, int requestCode, Bundle options) It work same as above , but it can take extra values in the shape of bundle with it 3 startActivityFromFragment(Fragment requestCode) It launches activity from the fragment you are currently inside fragment, Intent intent, int 4 startActivityFromFragment(Fragment requestCode, Bundle options) It not only launches the activity from the fragment , but can take extra values with it fragment, Intent intent, int 5

  48. Using Camera By using Camera Api This class is used for controlling device cameras. It can be used to take pictures when you are building a camera application. Camera API works in following ways: 1.Camera Manager: This is used to get all the cameras available in the device like front camera back camera each having the camera id. 2.CameraDevice: You can get it from Camera Manager class by its id. 3.CaptureRequest: You can create a capture request from camera device to capture images. 4.CameraCaptureSession: To get capture request s from Camera Device create a CameraCaptureSession. 5.CameraCaptureSession.CaptureCallback: This is going to provide the Capture session results.

  49. Checking Camera Permissions: For the first we have used the Function requestPermissions(new String[]{Manifest.permission.CAMERA},MY_CAMERA_PERMIS SION_CODE); We will check whether the user has given permissions or not if not then first we will ask the user for permissions if a user is using Android version above Android Marshmallow(API 23) because From Android Marshmallow(API 23) and above by default all dangerous permission disabled. When the App opens for the first time after installation then you have to grant permissions. But if the android version is below Marshmallow then this function won t be called. requestPermissions(newString[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE)

More Related Content

giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#giItT1WQy@!-/#