Android App Development (2)
Android App Development (2)
5.1 Activities
5.2 Intents
5.3 Fragments
6.1 SharedPreferences
8.3 Notifications
Key Features
• App Store Integration: Access to Google Play Store with millions of apps.
Use Cases
• IoT Devices
• Open Source: Available under Apache License; developers can modify the source code.
• Rich Development Environment: Integrated with debugging tools, memory and performance
profiling, and device emulation.
• Multimedia Support: Supports a wide range of audio, video, and image formats.
Key Features
• Others: Python (via third-party tools), Flutter (Dart), and React Native (JavaScript)
• Job Roles:
o Android Developer
o UI/UX Designer
o Firebase Engineer
• Growth Trends: Increasing demand in startups, fintech, edtech, and IoT sectors.
A. Prerequisites
Before starting with Android development, ensure the following prerequisites are met:
Android applications (especially those using Java) require the Java Development Kit (JDK).
Check Installation:
java -version
Steps:
1. Visit https://developer.android.com/studio
SDK Manager is where you manage Android versions and tools required to compile and run your
app.
3. Set:
o Name: HelloWorld
│ └── com.example.helloworld.MainActivity.java
Important files:
• activity_main.xml: UI layout
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
<TextView
android:id="@+id/helloText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center"
android:textSize="24sp"/>
Logcat is Android’s logging system that shows real-time logs while your app is running.
To use Logcat:
3. Build and run your first app on an emulator and your Android phone.
Android architecture is designed in a layered fashion. Each layer provides services to the layer above
it and utilizes the services of the layer below it.
• Provides:
o Hardware abstraction
o Memory management
o Networking
o Security settings
B. Native Libraries
• Converts .dex files into native instructions using ahead-of-time (AOT) compilation.
D. Application Framework
o Activity Manager
o Content Providers
o Resource Manager
o Notification Manager
o View System
• Developers write apps that run on this layer using the APIs from lower levels.
3.2 Components of Android Application
Android apps are built from four main components, each playing a unique role:
A. Activities
B. Services
o Playing music
o Downloading files
o Syncing data
C. Broadcast Receivers
• Examples:
o Battery low
o Connectivity changes
o SMS received
D. Content Providers
When you create a new project in Android Studio, several directories and files are auto-generated:
A. Manifest Folder
• Contains AndroidManifest.xml
• Declares:
o Package name
Example:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:label="MyApp"
android:icon="@mipmap/ic_launcher">
<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>
B. Java/Kotlin Folder
• Structured by packages
• Includes:
• values/:
D. Gradle Scripts
1. Project-level build.gradle
2. App-level build.gradle
o Contains:
▪ Application ID
▪ Dependencies (libraries)
▪ Versioning info
Example:
android {
compileSdkVersion 33
defaultConfig {
applicationId "com.example.myapp"
minSdkVersion 21
targetSdkVersion 33
versionCode 1
versionName "1.0"
dependencies {
implementation 'com.google.android.material:material:1.9.0'
}
• Draw the Android architecture in your notebook and label each layer.
• Create a dummy project and identify the use of each folder in the structure.
• Modify the manifest file to change app name and add an additional activity.
The User Interface (UI) in Android is built using XML layout files and connected with Java/Kotlin
code. Android offers a range of UI elements (widgets) like buttons, text fields, images, etc., that help
create visually engaging applications.
Key Concepts:
Android provides various types of layouts for positioning and aligning views.
A. LinearLayout
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:text="Welcome"/>
</LinearLayout>
C. ConstraintLayout
<androidx.constraintlayout.widget.ConstraintLayout>
<Button
android:id="@+id/myBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
D. FrameLayout
TextView
android:id="@+id/txtHello"
android:text="Hello, World!"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
EditText
<EditText
android:id="@+id/editName"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Button
<Button
android:id="@+id/btnSubmit"
android:text="Submit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
Java:
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
});
Kotlin:
btn.setOnClickListener {
ImageView
<ImageView
android:id="@+id/imageLogo"
android:layout_width="100dp"
android:layout_height="100dp"
android:src="@drawable/logo"/>
Example:
mp.start();
Toast
Snackbar
Like a toast but with an action button, ideal for user interaction.
Dialogs
new AlertDialog.Builder(this)
.setTitle("Exit")
.setNegativeButton("No", null)
.show();
o A welcome TextView
An Activity represents a single screen with a user interface in Android apps. It acts as the entry point
for user interaction.
3. onResume() – Called when the user can interact with the activity.
↓ ↑
onDestroy
Apps often need more than one screen, such as a login screen, dashboard, profile, etc. For each new
screen, we define a new Activity.
o SecondActivity.java / .kt
o activity_second.xml
<activity android:name=".SecondActivity"></activity>
Intents
An Intent is a messaging object used to request an action from another app component.
Types:
• Implicit Intent – Requests action from another app (e.g., open browser, call).
startActivity(intent);
intent.putExtra("username", "John");
intent.setData(Uri.parse("https://www.google.com"));
startActivity(intent);
Use startActivity() to move between activities. Optionally, use finish() to remove the current activity
from the stack.
startActivity(intent);
finish(); // Optional
The Android system manages a back stack of activities for navigation. Pressing the back button pops
the top activity off the stack.
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK) {
});
launcher.launch(intent);
In Android, data storage is crucial for saving user preferences, files, and databases. This section
covers various methods used to store data locally on an Android device.
6.1 SharedPreferences
SharedPreferences is used for storing small amounts of key-value data, such as login sessions,
settings, or user preferences.
Storing Data:
editor.putString("username", "JohnDoe");
editor.putBoolean("isLoggedIn", true);
editor.apply();
Retrieving Data:
Deleting Data:
editor.apply();
Used for storing private data within the app's internal directory.
Saving a File:
fos.write(data.getBytes());
fos.close();
Reading a File:
Log.d("FileRead", line);
fis.close();
Used for storing files on SD card or external shared directories (e.g., Downloads, Pictures).
Permissions Needed:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Checking Availability:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// Safe to write
SQLite is a lightweight relational database built into Android. It stores structured data locally.
onCreate(db);
Inserting Data:
SQLiteDatabase db = helper.getWritableDatabase();
values.put("name", "Alice");
Reading Data:
while (cursor.moveToNext()) {
Room is part of Android Jetpack and provides an abstraction over SQLite with annotations and
compile-time checks.
Define an Entity:
@Entity
@PrimaryKey(autoGenerate = true)
@Dao
@Insert
List<User> getAllUsers();
Database Class:
AppDatabase db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "my-database").build();
db.userDao().insertUser(new User("TestUser"));
}).start();
Practical Activities:
This module explores how to incorporate audio, video, images, and device sensors like accelerometer
and gyroscope into your Android applications to create more interactive and responsive experiences.
Android provides classes like MediaPlayer and VideoView to handle multimedia playback.
Controlling Playback:
mediaPlayer.pause(); // Pause
mediaPlayer.seekTo(0); // Rewind
mediaPlayer.stop(); // Stop
Release Resources:
mediaPlayer.release();
<VideoView
android:id="@+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
videoView.start();
Use MediaController for playback controls:
videoView.setMediaController(mediaController);
startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
@Override
imageView.setImageBitmap(imageBitmap);
• Accelerometer (motion)
• Gyroscope (rotation)
• Proximity sensor
• Light sensor
@Override
float y = event.values[1];
float z = event.values[2];
@Override
};
sensorManager.registerListener(sensorListener, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
@Override
super.onPause();
sensorManager.unregisterListener(sensorListener);
Recording Audio
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setOutputFile("/sdcard/record.3gp");
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
recorder.prepare();
recorder.start();
} catch (IOException e) {
e.printStackTrace();
Stop Recording:
recorder.stop();
recorder.release();
Permission Needed:
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
startActivityForResult(intent, PICK_IMAGE_REQUEST);
Handling Result:
@Override
imageView.setImageURI(selectedImage);
Practical Activities:
3. Record audio using the microphone and save the file to external storage.
This section will guide you through integrating Android applications with web services, including
calling RESTful APIs, parsing JSON data, and displaying results in your app using modern libraries.
Web Services allow apps to communicate over the internet, typically through HTTP.
A REST API provides access to server-side resources such as user profiles, product lists, etc., in
formats like JSON or XML.
While now deprecated for production, it's important to understand how AsyncTask was used to
perform background API calls.
try {
conn.setRequestMethod("GET");
String line;
result.append(line);
}
return result.toString();
} catch (Exception e) {
return null;
"email": "[email protected]"
try {
} catch (JSONException e) {
e.printStackTrace();
{"name": "Alice"},
{"name": "Bob"}
Retrofit is a powerful HTTP client for Android and Java, developed by Square.
Add Dependencies:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
@GET("users")
Call<List<User>> getUsers();
Model Class:
String name;
String email;
Retrofit Setup:
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
call.enqueue(new Callback<List<User>>() {
@Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
@Override
// Handle error
});
recyclerView.setAdapter(new UserAdapter(userList));
@FormUrlEncoded
@POST("register")
Call<ResponseBody> registerUser(
);
call.enqueue(new Callback<ResponseBody>() {
// success
}
public void onFailure(...) {
// error
});
Practical Activities:
4. Create a weather app using a free weather API and show current temperature.
Firebase is a powerful platform for building real-time applications, with features such as
authentication, real-time database, and cloud storage. This section will walk you through integrating
Firebase services into your Android app.
• Firebase Authentication
• Firebase Firestore
• Firebase Storage
Project-level build.gradle:
App-level build.gradle:
implementation 'com.google.firebase:firebase-auth:21.0.1'
implementation 'com.google.firebase:firebase-database:20.0.2'
Firebase Authentication allows you to easily authenticate users using different methods like
email/password, phone number, Google Sign-In, Facebook, etc.
// Register a user
mAuth.createUserWithEmailAndPassword("[email protected]", "password")
if (task.isSuccessful()) {
// Registration success
} else {
// Registration failure
}
});
// Log in a user
mAuth.signInWithEmailAndPassword("[email protected]", "password")
if (task.isSuccessful()) {
// Login success
} else {
// Login failure
});
Sign-Out:
mAuth.signOut();
Firebase Realtime Database is a cloud-hosted NoSQL database that supports real-time data syncing
between the client and server.
Storing Data:
myRef.setValue("John Doe");
Reading Data:
ref.addValueEventListener(new ValueEventListener() {
@Override
@Override
});
class User {
String name;
String email;
this.name = name;
this.email = email;
myRef.setValue(user);
Firestore is Firebase’s newer, more scalable NoSQL database. Unlike Realtime Database, Firestore
allows storing data in documents and collections.
FirebaseFirestore db = FirebaseFirestore.getInstance();
user.put("first", "John");
user.put("last", "Doe");
user.put("born", 1990);
db.collection("users")
.add(user)
.addOnSuccessListener(documentReference -> {
})
db.collection("users")
.get()
.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
} else {
});
FCM enables you to send notifications to users or devices. You can send notifications directly from
the Firebase console or via backend systems.
implementation 'com.google.firebase:firebase-messaging:23.0.0'
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
if (remoteMessage.getNotification() != null) {
<service
android:name=".MyFirebaseMessagingService"
android:exported="true">
<intent-filter>
</intent-filter>
</service>
Practical Activities:
3. Create a chat app using Firebase Realtime Database for real-time messaging.
Testing and debugging are critical steps in the development process to ensure that Android
applications function as expected and are free from bugs or crashes. This module will cover the best
practices for testing Android applications and debugging common issues.
• Unit Testing: Tests individual units or components of the application (e.g., methods, classes).
• UI Testing: Tests the UI interactions and ensures that the app responds correctly to user
input.
• Integration Testing: Ensures that components of the app work together as expected.
Unit Testing
Unit testing is the process of testing individual methods or functions. The most common framework
used for unit testing in Android is JUnit.
JUnit Example:
@Before
@Test
@Test
In this example, we test the add and subtract methods of a Calculator class.
UI Testing with Espresso
Espresso is an Android UI testing framework that allows you to simulate user interactions and verify
UI behaviors.
@Test
onView(withId(R.id.button))
.perform(click());
onView(withId(R.id.textView))
.check(matches(withText("Button clicked")));
This test simulates a button click and verifies that a TextView is updated correctly.
Integration Testing
Integration testing ensures that multiple components of the app work together correctly.
@Test
mockNetworkCall();
onView(withId(R.id.button)).perform(click());
onView(withId(R.id.textView)).check(matches(withText("Data loaded")));
Android Studio provides several tools to help developers identify and fix issues in their applications.
Logcat
Logcat is a system tool that provides detailed logs from Android devices. It is useful for tracking
errors, warnings, and debug messages.
• Access Logcat: In Android Studio, go to View > Tool Windows > Logcat.
• Log messages:
Log.d("TAG", "Debug message");
Log Levels:
• d - Debug
• e - Error
• i - Info
• w - Warning
• v - Verbose
Set breakpoints to pause execution at specific lines and inspect the variables, memory, and call stack.
• Set a Breakpoint: Click on the left margin next to the line number.
• Start Debugging: Click the Debug button in Android Studio (the bug icon) to run your app
with the debugger.
Debugging Commands:
• Step Out: Exit the current method and go back to the caller.
Android Profiler helps you monitor the performance of your app in real-time.
• Memory Profiler: Track memory usage and identify potential memory leaks.
• Network Profiler: Monitor network traffic and check if the app is consuming too much
bandwidth.
You can access these tools via View > Tool Windows > Profiler.
It's crucial to test your application on different devices and screen sizes to ensure a consistent
experience for all users.
You can create different virtual devices (AVDs) with different screen sizes, Android versions, and
device types (e.g., phone, tablet, wearable). This is essential for testing how your app behaves on
various devices.
• Create an AVD: Go to Tools > AVD Manager and create a new device profile.
• Run on Multiple Devices: You can run your app simultaneously on physical devices and
virtual devices to ensure compatibility.
Firebase Test Lab allows you to test your app on a range of real devices hosted in Google's data
centers. It can simulate real-world conditions and help you test on devices you don't own.
• Integrate Test Lab with Android Studio by linking your project to Firebase.
• Run tests on Firebase Test Lab: After configuring Firebase Test Lab in your project, run your
tests on physical devices hosted on Google’s servers.
Firebase App Distribution allows you to distribute your app to testers automatically after every build.
2. Upload your APK or AAB automatically using the Firebase CLI or Firebase Console.
You can automate the build, test, and deployment processes using Jenkins, GitHub Actions, or other
CI/CD tools.
Practical Activities:
5. Analyze your app's memory usage and identify memory leaks using Android Profiler.
6. Test your app on multiple devices and different screen sizes using AVDs.
This concludes the comprehensive course content for "Android Studio and Applications." You’ve now
covered the essential aspects of building Android apps from setup, coding, UI design, and
multimedia, to testing and debugging.