Android Unit 5
Android Unit 5
Google Maps Embed API Embed simple maps or Street View panoramas into web pages.
Google Maps Roads API Identify road segments and retrieve information about them.
Google Places API Web Search for places, businesses, and retrieve detailed
Service information.
Mobile APIs
Step 3: Now click on APIs & Services and open Dashboard from it.
To perform simple google maps activity or an application we have to give some permissions in our
AndroidMenifest.xml file. That is because of map needs to request to access certain features and
functionalities of the device and network.
1. <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
- This permission allows the application to change network connectivity state.
- Used to control the network connection, such as enabling/disabling mobile data or Wi-Fi.
- This permission is required if your app needs to programmatically manage network
connections.
2. <uses-permission android:name="android.permission.INTERNET"/>
- This permission allows the application to access the internet.
- It is a fundamental permission for applications that need to make network requests, fetch
data from remote servers, and perform online operations.
- Most apps that involve communication with servers or web services will require this
permission.
3. <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
- This permission allows the application to access approximate or coarse location
information.
- Coarse location refers to less precise location data that can be obtained quickly using
network-based methods, such as cell towers or Wi-Fi access points.
- It's commonly used for applications that need location information but don't require high
accuracy, such as weather apps or location-based advertisements.
4. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
- This permission allows the application to access precise or fine-grained location
information.
- Fine location data is obtained using GPS or other satellite-based methods, providing
higher accuracy compared to coarse location.
- Apps that require accurate location data, like navigation apps or fitness trackers, will
request this permission.
*Note: It is crucial to keep your API key secure and not expose it publicly, as it can be used to
access Google services under your account. If you plan to share your app's source code, consider
using techniques like storing the API key in a secure location or using environment variables to
keep the key confidential.
MapsActivity.java
package harsh.example.map;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import harsh.example.map.databinding.ActivityMapsBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Project: MAP
Here, in this Example I have mentioned longitude and latitude of a GCET College. That red symbol
is a Marker. For getting longitude and latitude of any place, press and hold on blue icon of location
in Google Map.
The type of map displayed can be modified dynamically by making a call to the setMapType()
method of the corresponding GoogleMap object, passing through one of the following values:
1. GoogleMap.MAP_TYPE_NONE An empty grid with no mapping tiles displayed.
2. GoogleMap.MAP_TYPE_NORMAL The standard view consisting of the classic road map.
3. GoogleMap.MAP_TYPE_SATELLITE - Displays the satellite imagery of the map region.
4. GoogleMap.MAP_TYPE_HYBRID - Displays satellite imagery with the road map superimposed.
5. GoogleMap.MAP_TYPE_TERRAIN - Displays topographical information such as contour lines
and colors.
Example:
MapsActivity.java
package harsh.example.differentmapviewexample;
import androidx.fragment.app.FragmentActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
noneMapBtn = findViewById(R.id.idBtnNoneMap);
normalMapBtn = findViewById(R.id.idBtnNormalMap);
satelliteMapBtn = findViewById(R.id.idBtnSatelliteMap);
hybridMapBtn = findViewById(R.id.idBtnHybridMap);
terrainMapBtn = findViewById(R.id.idBtnTerrainMap);
noneMapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
}
});
normalMapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
});
satelliteMapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
}
});
hybridMapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
}
});
terrainMapBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
}
});
}
activity_maps.xml
<fragment xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapsActivity" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_margin="5dp"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3">
<Button
android:id="@+id/idBtnNoneMap"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:singleLine="false"
android:text="None \n Map"
android:textAllCaps="false"
android:background="#800080"
android:textColor="@color/white" />
MAP_TYPE_TERRAIN MAP_TYPE_NORMAL
Project: DIFFERENTMAPVIEWEXAMPLE
<Button
android:id="@+id/getLocationButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="16dp"
android:text="Get Location" />
<TextView
android:id="@+id/locationTextView"
android:layout_width="wrap_content"
<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@+id/locationTextView"
android:layout_marginTop="16dp" />
</RelativeLayout>
MapsActivity.java
package harsh.example.currentlocationexample;
import android.os.Bundle;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import androidx.annotation.NonNull;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.tasks.OnSuccessListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);
locationTextView = findViewById(R.id.locationTextView);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
} else {
locationTextView.setText("Location not
available.");
}
}
});
} }
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull
String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_LOCATION_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
getLocation();
} else {
Toast.makeText(this, "Location permission denied.",
Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
Project: CURRENTLOCATIONEXAMPLE
Geocoding
- Geocoding is the process of transforming a description of a location-such as a pair of
coordinates, an address, or a name of a place-to a location on the earth's surface.
- Geocoding can best be described as the process of converting a textual based geographical
location (such as a street address) into geographical coordinates expressed in terms of
longitude and latitude.
- Geocoding can be done by entering one location description at a time or by providing many of
them at once in a table. The resulting locations are output as geographic features with
attributes, which can be used for mapping or spatial analysis.
- Geocoding can be achieved using the Android Geocoder class. An instance of the Geocoder class
can, for example, be passed a string representing a location such as a city name, street address
or airport code.
- The geocoder will attempt to find a match for the location and return a list of Address objects
that potentially match the location string, ranked in order with the closest match at position 0
in the list.
- A variety of information can then be extracted from the Address objects, including the
longitude and latitude of the potential matches.
Use of Geolocations
- Geolocation can be used to determine time zone and exact positioning coordinates, such as for
tracking wildlife or cargo shipments.
- Both mobile and desktop devices can use geolocation. There are apps which use location once,
and there are apps which continuously track your location as well. Some famous apps using
Geolocation are
1. Uber Cab booking
Effectiveness of Geocoder
- A system that provides geocoding is called a geocoding service (or just geocoder).
- To assess the effectiveness of a geocoder, you need to use two basic parameters:
1. The size of the database: The fuller the base, the more accurate and detailed the response
to the request will be. With a large database, the address can be specified up to the house
even in a small town.
2. Geocoding speed: The speed of a geocoder is determined by the number of requests
processed per second. The more requests the geocoder is able to handle, the more users the
system can service.
Example:
MapsActivity.java
package harsh.example.geocodingexample;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import java.io.IOException;
import java.util.List;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is
ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
@Override
public void onConnected(Bundle bundle) {
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURA
CY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int i) {
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,
this);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
} catch (IOException e) {
e.printStackTrace();
}
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(),
address.getLongitude());
mMap.addMarker(new
MarkerOptions().position(latLng).title(location));
mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
Toast.makeText(getApplicationContext(),address.getLatitude()+"
"+address.getLongitude(),Toast.LENGTH_LONG).show();
}
}
MediaPlayer
• Android is providing MediaPlayer class to access built-in media player services like playing
audio, video etc. In order to use MediaPlayer, we have to call a static Method create() of this
class. This method returns an instance of MediaPlayer class. Syntax:
MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);
• The second parameter is the name of the song that you want to play. You have to make a new
folder under your project with name raw and place the music file into it.
• Once you have created the MediaPlayer object you can call some methods to start or stop the
music. These methods are listed below.
mediaPlayer.start();
mediaPlayer.pause();
• On call to start() method, the music will start playing from the beginning. If this method is
called again after the pause() method, the music would start playing from where it is left and
not from the beginning.
• In order to start music from the beginning, you have to call reset() method. Its syntax is given
below.
Method Description
getDuration() It is used to get the total time duration of the song in milliseconds.
setAudioStreamType
it is used to specify the audio streaming type.
()
activity_main.xml
<ImageView
android:id="@+id/imgLogo"
android:layout_width="350dp"
android:layout_height="350dp"
android:layout_centerHorizontal="true"
android:layout_below="@+id/txtVw1"
android:layout_marginTop="10dp"
android:src="@drawable/cvm" />
<ImageButton
android:id="@+id/btnBackward"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginBottom="44dp"
android:layout_marginLeft="20dp"
android:src="@android:drawable/ic_media_rew" />
<ImageButton
android:id="@+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnBackward"
android:layout_marginLeft="20dp"
android:layout_toRightOf="@+id/btnBackward"
android:src="@android:drawable/ic_media_play" />
<ImageButton
MainActivity.java
package com.example.mediaplayerexample;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.SeekBar;
playbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Playing Audio",
Toast.LENGTH_SHORT).show();
mPlayer.start();
eTime = mPlayer.getDuration();
sTime = mPlayer.getCurrentPosition();
if(oTime == 0){
songPrgs.setMax(eTime);
oTime =1;
}
songTime.setText(String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(eTime),
TimeUnit.MILLISECONDS.toSeconds(eTime) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes(eTime))) );
startTime.setText(String.format("%d min, %d sec",
Project: MEDIAPLAYEREXAMPLE
Here, in this example I have created MediaPlayer object properties to play, pause song and changing
the song position either forward or backward, Here Forward/Backword is there for 5 seconds gap.
VideoPlayer
Method Description
Simple example of implementing a video player to play the video with multiple playback options
using VideoView and MediaController objects.
activity_main.xml
MainActivity.java
package com.example.videoplayerapp;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.VideoView;
import androidx.appcompat.app.AppCompatActivity;
Here, in this example video started playing directly and it’s having all media controls such as play,
pause, forward, backward, etc. options to control the video playing.
The android multimedia framework provides built-in support for capturing and encoding a variety
of common audio and video formats. We have a multiple way to record audio or video but by using
MediaRecorder class we can easily implement audio or video recording.
To record an audio, we need to use device’s microphone along with MediaRecorder class. In case, if
we want to record video, we need to use device’s camera along with MediaRecorder class.
Permissions required in android manifest file to record audio and save it in device.
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.STORAGE"/>
To use MediaRecord class to record an audio, we need to create an instance of MediaRecorder class and set
the source, output, encoding format and output file to store the recorded audio in device. After that we need
to call prepare(), start(), stop(), etc. to start the audio recording in our application.
Method Description
release() Releases the resources which are associated with MediaRecorder object.
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">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_launcher_foreground"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Record"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_alignParentLeft="true"
android:layout_marginTop="37dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play"
android:id="@+id/button3"
android:layout_alignTop="@+id/button2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP PLAYING RECORDING "
android:id="@+id/button4"
android:layout_below="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
/>
</RelativeLayout>
MainActivity.java
package com.example.recordingexample;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.app.ActivityCompat;
import android.os.Bundle;
import android.view.View;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Environment;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.Random;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" +
CreateRandomAudioFileName(5) + "AudioRecording.3gp";
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(MainActivity.this, "Recording
started",Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mediaRecorder.stop();
buttonStop.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
buttonStop.setEnabled(false);
buttonStart.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer.start();
buttonStopPlayingRecording.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
buttonStop.setEnabled(false);
buttonStart.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if(mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
MediaRecorderReady();
}
}
});
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
i++ ;
}
return stringBuilder.toString();
}
@Override
public void onRequestPermissionsResult(int requestCode, String
permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length> 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
Project: RECORDINGEXAMPLE
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/introbutton"
android:layout_width="1in"
android:layout_height="wrap_content"
android:onClick="playSound"
android:text="Introduction" />
<Button
android:id="@+id/generalsound"
android:layout_width="1in"
android:layout_height="wrap_content"
android:onClick="playSound"
android:text="sound 2" />
<Button
android:id="@+id/boostbutton"
android:layout_width="1in"
android:layout_height="wrap_content"
android:onClick="playSound"
android:text="Mario Boost" />
<Button
android:id="@+id/jumbpsound"
android:layout_width="1in"
android:layout_height="wrap_content"
android:onClick="playSound"
android:text="Mario Jump" />
<Button
android:id="@+id/gameoverbutton"
android:layout_width="1in"
android:layout_height="wrap_content"
android:onClick="playSound"
MainActivity.java
package com.example.soundpoolexample;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Project: SOUNDPOOLEXAMPLE
SoundPool Vs MediaPlayer
Use Case Short, simple audio effects Longer audio tracks, music, streaming
Performance Efficient for short sounds Suitable for longer tracks
Memory Management Efficient for multiple sounds Can be less memory efficient
Android Camera
Camera is useful to capture the photos and videos in our applications. By using camera API we can
control the functionalities of camera based on our requirements.
Android framework provides a two ways such as android.hardware.camera2 API and camera intent
to capture the images and videos in our application.
android.hardware.camera2
It is a primary API for controlling the device cameras. By using this we can take the pictures or
videos from our application using camera.
Intent
We can capture the photos or videos without directly using the Camera object by using Intent action
types either MediaStore.ACTION_IMAGE_CAPTURE or MediaStore.ACTION_VIDEO_CAPTURE.
Intent cInt = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cInt,Image_Capture_Code);
Example
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<Button
android:id="@+id/btnTakePicture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take a Photo"
android:textStyle="bold"
MainActivity.java
package com.example.cameraapplication;
import android.content.Intent;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
When we click on Take a Photo button, the camera will start and we can take the picture of whatever
we want, the captured image will be shown in defined ImageView.
Project: CAMERAAPPLICATION
Video Recording
Video Recording is a most common feature which we can currently get to see in many android
applications.
This feature is mostly seen used in payments applications where the application has to verify the
identity of the user for authentication as well as doing their KYC. Here, we will see How to record a
video within our android application.
I have build a simple android application in which I will display button and a VideoView in which
when someone click on a button, recording of video will be started and once the video recording is
done, that video will be played in VideoView.
Example:
activity_main.xml
MainActivity.java
package com.example.videorecorder;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import androidx.annotation.Nullable;
import android.content.Intent;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.VideoView;
public class MainActivity extends AppCompatActivity {
// creating variables on below line.
private Button recordVideoBtn;
private VideoView videoView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Project: VIDEORECORDER