0% found this document useful (0 votes)
20 views

unit-4 mobile application development

Uploaded by

Lokesh Pck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

unit-4 mobile application development

Uploaded by

Lokesh Pck
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

UNIT IV ANDROID USER INTERFACE DESIGN & MULTIMEDIA

User Interface Screen elements, Designing User Interfaces with Layouts, Drawing and Working with
Anima on. Playing Audio and Video, Recording Audio and Video, Using the Camera to Take and
Process Pictures

1) User Interface Screen elements


User Interface (UI) Screen Elements in Android

Android provides a wide variety of screen elements (also known as widgets) to design intui ve and interac ve user interfaces
(UIs). These elements are part of the Android UI toolkit and are categorized into View and ViewGroup classes.

Basic UI Components (Views)

1. TextView

o Displays text to the user.

o Can show sta c or dynamic text.

o Example:

o <TextView

o android:id="@+id/textView"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Hello, World!"

o android:textSize="18sp"

o android:textColor="#000000" />

2. EditText

o A text field for user input.

o Can be customized for input types like password, number, or email.

o Example:

o <EditText

o android:id="@+id/editText"

o android:layout_width="match_parent"

o android:layout_height="wrap_content"

o android:hint="Enter your name" />

3. Bu on

o A clickable bu on for user interac on.

o Example:

o <Bu on

o android:id="@+id/bu on"

o android:layout_width="wrap_content"
o android:layout_height="wrap_content"

o android:text="Click Me" />

4. ImageView

o Displays images in the app.

o Example:

o <ImageView

o android:id="@+id/imageView"

o android:layout_width="100dp"

o android:layout_height="100dp"

o android:src="@drawable/ic_launcher_foreground" />

5. CheckBox

o A two-state toggle (checked/unchecked).

o Example:

o <CheckBox

o android:id="@+id/checkBox"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Accept terms" />

6. RadioBu on

o Used with a RadioGroup to allow one selec on out of a group.

o Example:

o <RadioGroup

o android:layout_width="wrap_content"

o android:layout_height="wrap_content">

o <RadioBu on

o android:id="@+id/radioBu on1"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Op on 1" />

o <RadioBu on

o android:id="@+id/radioBu on2"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Op on 2" />

o </RadioGroup>

7. ToggleBu on / Switch
o Provides a toggle switch for on/off func onality.

o Example:

o <Switch

o android:id="@+id/switch"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Switch" />

8. ProgressBar

o Shows a loading or progress indicator.

o Example:

o <ProgressBar

o android:id="@+id/progressBar"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:indeterminate="true" />

9. SeekBar

o A slider to choose a value within a range.

o Example:

o <SeekBar

o android:id="@+id/seekBar"

o android:layout_width="match_parent"

o android:layout_height="wrap_content" />

10. Spinner

o A dropdown menu for selec ng an item.

o Example:

o <Spinner

o android:id="@+id/spinner"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content" />

Containers (ViewGroups)

1. LinearLayout

o Arranges child elements in a single row or column.

o Example:

o <LinearLayout

o android:layout_width="match_parent"
o android:layout_height="wrap_content"

o android:orienta on="ver cal">

o <TextView

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Text inside LinearLayout" />

o <Bu on

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Bu on" />

o </LinearLayout>

2. Rela veLayout (Deprecated in favor of ConstraintLayout)

o Posi ons child views rela ve to each other or the parent container.

o Example:

o <Rela veLayout

o android:layout_width="match_parent"

o android:layout_height="wrap_content">

o <TextView

o android:id="@+id/textView"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Rela ve Layout Text" />

o <Bu on

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:layout_below="@id/textView"

o android:text="Bu on" />

o </Rela veLayout>

3. ConstraintLayout

o A flexible and efficient layout that allows posi oning and aligning views using constraints.

o Example:

o <ConstraintLayout

o android:layout_width="match_parent"

o android:layout_height="match_parent">

o
o <Bu on
o android:id="@+id/bu on"

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:layout_marginTop="100dp"

o app:layout_constraintTop_toTopOf="parent"

o app:layout_constraintStart_toStartOf="parent"

o app:layout_constraintEnd_toEndOf="parent"

o android:text="Bu on" />

o </ConstraintLayout>

4. FrameLayout

o A simple layout that stacks child views on top of each other.

o Example:

o <FrameLayout

o android:layout_width="match_parent"

o android:layout_height="match_parent">

o <ImageView

o android:layout_width="match_parent"

o android:layout_height="match_parent"

o android:src="@drawable/background_image" />

o <TextView

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Overlay Text"

o android:layout_gravity="center" />

o </FrameLayout>

5. ScrollView

o A container that allows ver cal scrolling of its content.

o Example:

o <ScrollView

o android:layout_width="match_parent"

o android:layout_height="match_parent">

o <LinearLayout

o android:layout_width="match_parent"

o android:layout_height="wrap_content"

o android:orienta on="ver cal">

o <!-- Child views -->


o </LinearLayout>

o </ScrollView>

6. RecyclerView

o A more advanced and efficient list container compared to ListView.

o Requires an adapter for managing data.

o Example:

o <androidx.recyclerview.widget.RecyclerView

o android:id="@+id/recyclerView"

o android:layout_width="match_parent"

o android:layout_height="match_parent" />

Other Advanced Elements

1. CardView

o A layout that provides a card-like appearance.

o Example:

o <androidx.cardview.widget.CardView

o android:layout_width="match_parent"

o android:layout_height="wrap_content"

o app:cardEleva on="4dp"

o app:cardCornerRadius="8dp">

o <TextView

o android:layout_width="wrap_content"

o android:layout_height="wrap_content"

o android:text="Card Content" />

o </androidx.cardview.widget.CardView>

2. WebView

o Used to display web pages or HTML content within the app.

o Example:

o <WebView

o android:id="@+id/webView"

o android:layout_width="match_parent"

o android:layout_height="match_parent" />

3. Toolbar

o A modern replacement for the Ac onBar, providing greater customiza on.

o Example:

o <androidx.appcompat.widget.Toolbar
o android:id="@+id/toolbar"

o android:layout_width="match_parent"

o android:layout_height="wrap_content"

o android:background="?a r/colorPrimary"

o android: tle="My App Toolbar" />

Key A ributes for UI Elements

 layout_width and layout_height: Define size (match_parent, wrap_content, or specific values like 100dp).

 id: Unique iden fier for the element.

 gravity: Align content within the element.

 padding and margin: Define spacing.

 background: Set the background color or drawable.

 visibility: Controls visibility (visible, invisible, gone).

By combining these UI elements, Android developers can create complex and visually appealing user interfaces that meet the
needs of their applica ons.

2) Designing User Interfaces with Layouts


Designing User Interfaces with Layouts in Android

In Android, layouts are used to arrange and organize UI components (Views) on the screen. A layout defines the
structure for a user interface in your app, specifying how the UI components (widgets) are displayed, aligned, and
nested. Layouts are defined either in XML files or programma cally in Java/Kotlin.

Types of Layouts

1. LinearLayout

 Descrip on: Arranges child views in a single row (horizontal) or column (ver cal).

 Key A ributes:

o orienta on: Specifies the layout's direc on (ver cal or horizontal).

o gravity: Aligns all child views in a specific direc on.

o layout_weight: Allocates space propor onally among children.

 Example:

 <LinearLayout

 android:layout_width="match_parent"

 android:layout_height="match_parent"

 android:orienta on="ver cal">

 <TextView

 android:layout_width="wrap_content"
 android:layout_height="wrap_content"

 android:text="Hello, World!" />

 <Bu on

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:text="Click Me" />

 </LinearLayout>

2. Rela veLayout (Deprecated in favor of ConstraintLayout)

 Descrip on: Posi ons child views rela ve to each other or to the parent container.

 Key A ributes:

o layout_alignParentTop, layout_centerInParent, etc., for alignment within the parent.

o layout_below, layout_toRightOf, etc., for rela ve posi oning.

 Example:

 <Rela veLayout

 android:layout_width="match_parent"

 android:layout_height="match_parent">

 <TextView

 android:id="@+id/textView"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:text="Hello!" />

 <Bu on

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_below="@id/textView"

 android:text="Click Me" />

 </Rela veLayout>

3. ConstraintLayout

 Descrip on: A flexible layout that allows you to posi on and size widgets by defining constraints rela ve to
other widgets or the parent container.

 Key Features:

o Eliminates nested layouts for be er performance.


o Supports chains, barriers, and guidelines.

 Example:

 <androidx.constraintlayout.widget.ConstraintLayout

 android:layout_width="match_parent"

 android:layout_height="match_parent">

 <Bu on

 android:id="@+id/bu on"

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_marginTop="16dp"

 app:layout_constraintTop_toTopOf="parent"

 app:layout_constraintStart_toStartOf="parent"

 app:layout_constraintEnd_toEndOf="parent"

 android:text="Centered Bu on" />

 </androidx.constraintlayout.widget.ConstraintLayout>

4. FrameLayout

 Descrip on: A simple layout that stacks child views on top of each other.

 Use Case: Overlaying content, such as a progress indicator over an image.

 Example:

 <FrameLayout

 android:layout_width="match_parent"

 android:layout_height="match_parent">

 <ImageView

 android:layout_width="match_parent"

 android:layout_height="match_parent"

 android:src="@drawable/sample_image" />

 <ProgressBar

 android:layout_width="wrap_content"

 android:layout_height="wrap_content"

 android:layout_gravity="center" />

 </FrameLayout>
5. TableLayout

 Descrip on: Arranges child views in a tabular format with rows and columns.

 Key A ributes:

o TableRow defines a single row in the table.

 Example:

 <TableLayout

 android:layout_width="match_parent"

 android:layout_height="wrap_content">

 <TableRow>

 <TextView

 android:text="Row 1, Col 1" />

 <TextView

 android:text="Row 1, Col 2" />

 </TableRow>

 <TableRow>

 <TextView

 android:text="Row 2, Col 1" />

 <TextView

 android:text="Row 2, Col 2" />

 </TableRow>

 </TableLayout>

6. ScrollView

 Descrip on: A container that allows scrolling for content that exceeds the screen size.

 Usage:

o Can only have one child view (usually a layout like LinearLayout).

 Example:

 <ScrollView

 android:layout_width="match_parent"

 android:layout_height="match_parent">

 <LinearLayout

 android:layout_width="match_parent"
 android:layout_height="wrap_content"

 android:orienta on="ver cal">

 <TextView

 android:text="Scrollable Content" />

 <!-- Add more child views -->

 </LinearLayout>

 </ScrollView>

7. GridLayout

 Descrip on: Places child views in a rectangular grid.

 Key A ributes:

o layout_row and layout_column: Specify the cell's row and column.

 Example:

 <GridLayout

 android:layout_width="match_parent"

 android:layout_height="wrap_content"

 android:rowCount="2"

 android:columnCount="2">

 <TextView

 android:text="Cell 1,1" />

 <TextView

 android:text="Cell 1,2" />

 <TextView

 android:text="Cell 2,1" />

 <TextView

 android:text="Cell 2,2" />

 </GridLayout>

Choosing the Right Layout

 Use ConstraintLayout for complex and efficient layouts.

 Use LinearLayout for simple, single-direc onal arrangements.

 Use FrameLayout for overlays or stack-based content.

 Use ScrollView for scrolling content.


 Use GridLayout or TableLayout for grid-based designs.

Best Prac ces for Layout Design

1. Use ConstraintLayout:

o Minimize nes ng of layouts for be er performance.

o Replace nested LinearLayout or Rela veLayout with a single ConstraintLayout.

2. Avoid Hardcoding Dimensions:

o Use match_parent and wrap_content where possible.

o Define dimensions in dp (density-independent pixels) for consistency across devices.

3. Support Mul ple Screen Sizes:

o Use res/layout for default layouts.

o Create addi onal layouts in res/layout-sw600dp, res/layout-land, etc., for larger screens or
orienta ons.

4. Test for Accessibility:

o Ensure proper text scaling by using sp for text sizes.

o Provide descrip ve contentDescrip on for accessibility tools.

5. Leverage Layout Tools:

o Use Android Studio’s Layout Editor for a visual representa on of the design.

o Use the A ributes Panel to tweak UI proper es in real- me.

By using layouts effec vely, developers can create visually appealing and highly func onal UIs for Android
applica ons, ensuring a smooth and intui ve user experience.

3) Drawing and Working with Anima on.


Drawing and Working with Anima on in Android

Android provides a robust framework for crea ng custom drawings and anima ons to enhance user interfaces. These features
allow developers to create visually appealing effects, transi ons, and interac ve elements.

1. Drawing in Android

Custom drawings are implemented using the Canvas API and Paint objects in Android. You can use these to create custom views or
graphical elements.

Custom Drawing

 Custom drawing is done by overriding the onDraw() method in a custom View class.

 Use the Canvas object to draw shapes, text, or bitmaps.

Example: Custom Drawing

public class CustomView extends View {


private Paint paint;

public CustomView(Context context) {

super(context);

paint = new Paint();

paint.setColor(Color.RED);

paint.setStyle(Paint.Style.FILL);

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

// Draw a circle

canvas.drawCircle(150, 150, 100, paint);

Usage in Layout

<com.example.CustomView

android:layout_width="match_parent"

android:layout_height="match_parent" />

Common Drawing Methods

 drawRect(): Draw a rectangle.

 drawCircle(): Draw a circle.

 drawLine(): Draw a line.

 drawText(): Draw text.

 drawBitmap(): Draw an image.

2. Working with Anima ons

Anima ons in Android are used to bring life to your UI by adding mo on and transi ons. Android provides mul ple types of
anima on frameworks:

a. Property Anima ons

Property anima on is the most powerful and flexible anima on system in Android. It allows you to animate any object property.

Key Classes

 ObjectAnimator: Animates a specific property of an object.

 AnimatorSet: Groups mul ple anima ons together.

 ValueAnimator: Provides anima on data that can be applied manually.


Example: ObjectAnimator

ObjectAnimator anima on = ObjectAnimator.ofFloat(view, "transla onX", 0f, 100f);

anima on.setDura on(1000); // 1 second

anima on.start();

Example: AnimatorSet

AnimatorSet animatorSet = new AnimatorSet();

ObjectAnimator moveX = ObjectAnimator.ofFloat(view, "transla onX", 0f, 200f);

ObjectAnimator fadeOut = ObjectAnimator.ofFloat(view, "alpha", 1f, 0f);

animatorSet.playTogether(moveX, fadeOut);

animatorSet.setDura on(1000);

animatorSet.start();

b. View Anima ons

These anima ons are used for simple transforma ons like moving, fading, rota ng, or scaling.

XML Example

<!-- res/anim/translate.xml -->

<translate

xmlns:android="h p://schemas.android.com/apk/res/android"

android:fromXDelta="0%"

android:toXDelta="100%"

android:dura on="1000" />

Usage in Code

Anima on anima on = Anima onU ls.loadAnima on(context, R.anim.translate);

view.startAnima on(anima on);

Types of View Anima ons

1. TranslateAnima on: Moves the view from one point to another.

2. ScaleAnima on: Changes the size of the view.

3. RotateAnima on: Rotates the view.

4. AlphaAnima on: Changes the transparency of the view.

c. Drawable Anima ons

Drawable anima ons are frame-by-frame anima ons using a sequence of drawable resources.

Example: Frame-by-Frame Anima on

<!-- res/drawable/anima on_list.xml -->

<anima on-list xmlns:android="h p://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/frame1" android:dura on="100" />

<item android:drawable="@drawable/frame2" android:dura on="100" />

<item android:drawable="@drawable/frame3" android:dura on="100" />


</anima on-list>

Usage in Code

ImageView imageView = findViewById(R.id.imageView);

imageView.setBackgroundResource(R.drawable.anima on_list);

Anima onDrawable anima onDrawable = (Anima onDrawable) imageView.getBackground();

anima onDrawable.start();

d. Physics-Based Anima ons

Physics-based anima ons (introduced in Android API 16+) simulate realis c mo on such as springs and flings.

Spring Anima on

SpringAnima on springAnima on = new SpringAnima on(view, SpringAnima on.TRANSLATION_Y, 0);

springAnima on.getSpring().setDampingRa o(SpringForce.DAMPING_RATIO_MEDIUM_BOUNCY);

springAnima on.getSpring().setS ffness(SpringForce.STIFFNESS_LOW);

springAnima on.start();

3. Transi on Framework

Transi ons animate the movement, addi on, or removal of views in a scene.

Usage Example

Transi on transi on = new Fade();

transi on.setDura on(500); // 500ms

Transi onManager.beginDelayedTransi on(viewGroup, transi on);

view.setVisibility(View.GONE); // Triggers the anima on

4. Advanced: Custom Anima ons

You can combine anima ons and use interpolators to achieve custom effects.

Custom Interpolators

Interpolators define the rate of change for anima ons. Android provides several interpolators like:

 LinearInterpolator

 AccelerateInterpolator

 BounceInterpolator

Example: Bounce Effect

ObjectAnimator anima on = ObjectAnimator.ofFloat(view, "transla onY", 0f, 300f);

anima on.setDura on(1000);

anima on.setInterpolator(new BounceInterpolator());

anima on.start();

Best Prac ces for Anima ons


1. Keep Anima ons Smooth:

o Avoid heavy computa ons during anima ons.

o Use hardware accelera on where possible.

2. Use Anima ons Sparingly:

o Ensure they enhance the user experience, not distract.

3. Op mize Performance:

o Test anima ons on lower-end devices.

o Minimize the use of frame-by-frame anima ons due to resource intensity.

4. Leverage Tools:

o Use Android Studio's Layout Inspector and Profiler to debug and op mize anima ons.

By combining drawing and anima on techniques, you can create highly interac ve and visually compelling Android applica ons.

4) Playing Audio and Video, Recording Audio and Video


Playing and Recording Audio and Video in Android

Android provides a comprehensive framework for handling media tasks such as playing and recording audio and video. Developers
can u lize these features to integrate mul media func onality into their applica ons.

Playing Audio

Android uses the MediaPlayer class to play audio files.

Playing an Audio File

Steps:

1. Ini alize the MediaPlayer with an audio file.

2. Call prepare() or prepareAsync() to load the file.

3. Use start() to play the audio.

Example: Playing an Audio File from the Raw Folder

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.sample_audio);

mediaPlayer.start();

Control Audio Playback

mediaPlayer.pause(); // Pause playback

mediaPlayer.stop(); // Stop playback

mediaPlayer.release(); // Release resources

Streaming Audio

For streaming audio from the internet:

MediaPlayer mediaPlayer = new MediaPlayer();

mediaPlayer.setDataSource("h p://example.com/audio.mp3");

mediaPlayer.prepareAsync();

mediaPlayer.setOnPreparedListener(mp -> mp.start());


Playing Video

Android uses the VideoView class and MediaPlayer for video playback.

Playing a Video in a VideoView

1. Add a VideoView to your layout.

2. Set the video source.

3. Use the start() method to play.

XML Layout

<VideoView

android:id="@+id/videoView"

android:layout_width="match_parent"

android:layout_height="match_parent" />

Java Code

VideoView videoView = findViewById(R.id.videoView);

videoView.setVideoPath("android.resource://" + getPackageName() + "/" + R.raw.sample_video);

videoView.start();

Customizing Video Playback

 Use MediaController for playback controls:

 MediaController mediaController = new MediaController(this);

 videoView.setMediaController(mediaController);

 mediaController.setAnchorView(videoView);

Recording Audio

Android provides the MediaRecorder class for audio recording.

Steps to Record Audio

1. Check for microphone permissions in AndroidManifest.xml:

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

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

4. Ini alize MediaRecorder and configure it.

5. Start and stop recording.

Example: Recording Audio

MediaRecorder recorder = new MediaRecorder();

recorder.setAudioSource(MediaRecorder.AudioSource.MIC);

recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);

recorder.setOutputFile("/sdcard/recorded_audio.3gp");

recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {

recorder.prepare();

recorder.start();

} catch (IOExcep on e) {

e.printStackTrace();

// Stop recording

recorder.stop();

recorder.release();

Recording Video

The MediaRecorder class also supports video recording.

Steps to Record Video

1. Check for camera and storage permissions in AndroidManifest.xml:

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

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

4. Ini alize MediaRecorder.

5. A ach a Camera or SurfaceView as a preview display.

Example: Recording Video

MediaRecorder mediaRecorder = new MediaRecorder();

mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);

mediaRecorder.setOutputFile("/sdcard/recorded_video.mp4");

mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());

try {

mediaRecorder.prepare();

mediaRecorder.start();

} catch (IOExcep on e) {

e.printStackTrace();

// Stop recording

mediaRecorder.stop();

mediaRecorder.release();
Best Prac ces

Permissions

 For Android 6.0+ (API 23), request run me permissions for recording and storage:

 Ac vityCompat.requestPermissions(this,

 new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, REQUEST_CODE);

Error Handling

 Handle excep ons like IOExcep on and IllegalStateExcep on.

 Use setOnErrorListener() for MediaPlayer and MediaRecorder.

Resource Management

 Always call release() on MediaPlayer and MediaRecorder to free up system resources.

Advanced Features

1. Audio Focus Handling: Manage audio focus using the AudioManager to avoid conflicts with other apps.

2. AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

3. audioManager.requestAudioFocus(...);

4. Background Playback: Use a Service to play audio or video in the background.

5. Camera2 API: For advanced video recording features like real- me filters and high-resolu on support, use the Camera2 API.

6. ExoPlayer: For more control and flexibility, consider using ExoPlayer, an open-source media player developed by Google.

By leveraging these capabili es, you can build feature-rich mul media applica ons for Android.

5) Using the Camera to Take and Process Pictures


Using the Camera to Take and Process Pictures in Android

Android provides APIs for integra ng camera func onality into your applica on. You can launch the camera app to capture
pictures or use the Camera2 API to control the camera hardware directly.

1. Launching the Camera App to Capture Pictures

You can launch the device's na ve camera app using an Intent and retrieve the captured image in your app.

Steps to Launch the Camera App

1. Add Permissions: Request camera and storage permissions in the AndroidManifest.xml:

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

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

4. Create a File to Save the Image:

o Use the FileProvider to securely share the file loca on with the camera app.

5. Launch the Camera Intent:

o Use MediaStore.ACTION_IMAGE_CAPTURE.

6. Handle the Result:

o Retrieve the captured image in onAc vityResult().


Example Code: Capture Picture Using Camera Intent

// Declare a URI for saving the image

private Uri photoUri;

private void openCamera() {

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// Create a file to store the image

File photoFile = createImageFile();

if (photoFile != null) {

photoUri = FileProvider.getUriForFile(this, "com.example.fileprovider", photoFile);

intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

startAc vityForResult(intent, REQUEST_IMAGE_CAPTURE);

// Method to create a file for the image

private File createImageFile() {

String meStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());

String imageFileName = "JPEG_" + meStamp + "_";

File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

File image = null;

try {

image = File.createTempFile(imageFileName, ".jpg", storageDir);

} catch (IOExcep on e) {

e.printStackTrace();

return image;

// Handle the result in onAc vityResult

@Override

protected void onAc vityResult(int requestCode, int resultCode, Intent data) {

super.onAc vityResult(requestCode, resultCode, data);

if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

// The image is saved at photoUri

// You can now display or process the image

}
}

2. Capturing Pictures Using the Camera2 API

For more control over the camera (e.g., resolu on, focus, exposure), use the Camera2 API. This API provides fine-grained control of
camera hardware and is preferred for advanced camera func onality.

Steps to Use the Camera2 API

1. Add Permissions:

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

3. Set Up a TextureView:

o The TextureView acts as a preview surface for the camera feed.

4. Open the Camera:

o Use CameraManager to access the camera device.

5. Capture the Image:

o Use CaptureRequest and CameraCaptureSession.

Example Code: Basic Camera2 Implementa on

private void openCamera() {

CameraManager cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

try {

String cameraId = cameraManager.getCameraIdList()[0]; // Get the rear-facing camera

cameraManager.openCamera(cameraId, new CameraDevice.StateCallback() {

@Override

public void onOpened(@NonNull CameraDevice camera) {

// Camera is open, start preview

createCameraPreviewSession(camera);

@Override

public void onDisconnected(@NonNull CameraDevice camera) {

camera.close();

@Override

public void onError(@NonNull CameraDevice camera, int error) {

camera.close();

}, null);

} catch (CameraAccessExcep on e) {

e.printStackTrace();
}

// Method to create a preview session

private void createCameraPreviewSession(CameraDevice cameraDevice) {

SurfaceTexture texture = textureView.getSurfaceTexture();

texture.setDefaultBufferSize(previewWidth, previewHeight);

Surface surface = new Surface(texture);

try {

CaptureRequest.Builder previewRequestBuilder =

cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

previewRequestBuilder.addTarget(surface);

cameraDevice.createCaptureSession(Arrays.asList(surface),

new CameraCaptureSession.StateCallback() {

@Override

public void onConfigured(@NonNull CameraCaptureSession session) {

// Start the preview

CaptureRequest previewRequest = previewRequestBuilder.build();

try {

session.setRepea ngRequest(previewRequest, null, null);

} catch (CameraAccessExcep on e) {

e.printStackTrace();

@Override

public void onConfigureFailed(@NonNull CameraCaptureSession session) {

// Handle failure

}, null);

} catch (CameraAccessExcep on e) {

e.printStackTrace();

3. Processing Captured Images


Once you capture an image, you can process it, such as resizing, cropping, or applying filters.

Common Image Processing Tasks

1. Display the Image:

o Use an ImageView to display the captured picture.

2. Resize or Crop the Image:

o Use the Bitmap class for image manipula on:

o Bitmap bitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());

o Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);

3. Save the Processed Image:

o Use the FileOutputStream class to save modified images.

4. Best Prac ces

 Check Camera Availability:

 PackageManager packageManager = getPackageManager();

 if (!packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {

 // No camera available

 }

 Handle Permissions: For Android 6.0+ (API 23), request run me permissions:

 Ac vityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE);

 Use Async Tasks: Perform image processing in a background thread to prevent blocking the UI.

 Handle Orienta on: Adjust the image orienta on using ExifInterface:

 ExifInterface exif = new ExifInterface(photoFile.getAbsolutePath());

 String orienta on = exif.getA ribute(ExifInterface.TAG_ORIENTATION);

 Op mize Storage: Save images in appropriate formats (e.g., JPEG) and compress them to reduce file size.

By leveraging Android's camera APIs and processing capabili es, you can create powerful mul media applica ons that allow users
to capture and edit images seamlessly.

You might also like