Mad QB Ut 2
Mad QB Ut 2
2nd Unit
Vedant Jagadale
CHAPTER FOUR
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:contentDescription="App logo button"
android:scaleType="centerCrop"
android:background="@android:color/transparent"/>
2) Write a program to create a toggle button to display ON/OFF Bluetooth on the display
screen
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"
tools:context=".MainActivity"
android:gravity="center">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/text"
android:layout_marginTop="10dp"
android:textSize="20sp"
android:textStyle="bold"
/>
<ToggleButton
android:id="@+id/toggleBluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Bluetooth ON"
android:textOff="Bluetooth OFF"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" "
android:id="@+id/status"
android:layout_below="@id/text"
android:layout_marginTop="40dp"
android:layout_marginStart="100dp"
android:textColor="@color/red"/>
</RelativeLayout>
(don’t add any colour in xml if you then u will have to add one more colour file eg:)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="red">#DE0A0A </color>
</resources>
JAVA:
package com.example.toggelbutton;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (button.isChecked()) {
status.setText("Bluetooth is On");
} else {
status.setText("Bluetooth is Off");
}
}
});
}
}
5) Write a program to show radio buttons with and without radio group.
JAVA:
package com.example.radiobuttonexample;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
RadioButton radioButton1, radioButton2, maleRadioButton, femaleRadioButton;
RadioGroup radioGroup;
Button showSelectedButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Individual Radio Buttons (Without RadioGroup)
radioButton1 = findViewById(R.id.radioButton1);
radioButton2 = findViewById(R.id.radioButton2);
// Radio Buttons inside a RadioGroup
radioGroup = findViewById(R.id.radioGroup);
maleRadioButton = findViewById(R.id.maleRadioButton);
femaleRadioButton = findViewById(R.id.femaleRadioButton);
// Button to Show Selected Option
showSelectedButton = findViewById(R.id.showSelectedButton);
showSelectedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String selectedText = "";
// Check standalone radio buttons
if (radioButton1.isChecked()) {
selectedText = "Selected: Radio Button 1";
} else if (radioButton2.isChecked()) {
selectedText = "Selected: Radio Button 2";
}
// Check RadioGroup selection
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == R.id.maleRadioButton) {
selectedText = "Selected: Male";
} else if (selectedId == R.id.femaleRadioButton) {
selectedText = "Selected: Female";
}
// Show Toast Message
Toast.makeText(MainActivity.this, selectedText, Toast.LENGTH_SHORT).show();
}
});
}
}
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="20dp">
<!-- Circular Progress Bar -->
<ProgressBar
android:id="@+id/circularProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@android:style/Widget.ProgressBar.Large"
android:indeterminate="true"/>
</LinearLayout>
JAVA file:
package com.example.circularprogressbar;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
1. Basic Attributes:
o android:src: Sets a drawable as the content of the ImageView
o android:contentDescription: Accessibility description of the image
o android:adjustViewBounds: Adjusts the ImageView bounds to preserve the
aspect ratio of the image
o android:baseline: The offset of the baseline within this view
o android:baselineAlignBottom: If true, the ImageView baseline will be the
bottom of the image
2. Scaling Attributes:
o android:scaleType: Defines how the image should be scaled
matrix: Scale using the image matrix
fitXY: Scale X and Y independently to fit exactly
fitStart: Scale maintaining aspect ratio, aligned to top-left
fitCenter: Scale maintaining aspect ratio, centered
fitEnd: Scale maintaining aspect ratio, aligned to bottom-right
center: Center without scaling
centerCrop: Scale uniformly to fill, cropping if needed
centerInside: Scale uniformly to fit inside, no cropping
o android:cropToPadding: If true, the image will be cropped to the padding
3. Tinting Attributes:
o android:tint: Tint color for the image
o android:tintMode: Blending mode for the tint
4. Background Attributes:
o android:background: Background drawable
o android:alpha: Alpha value for the image
5. Padding Attributes:
o android:padding: Padding for all edges
o android:paddingLeft, android:paddingRight, etc.
6. Layout Attributes:
o android:layout_width, android:layout_height
o android:layout_margin, etc.
8) Describe android:stretchMode attribute of Grid View in detail
The android:stretchMode attribute in GridView determines how columns should
stretch to fill the available space when there's extra space not occupied by columns.
This is particularly useful when the GridView's width doesn't perfectly match the
combined width of all columns.
This attribute is particularly important for making GridView layouts that look good
across different screen sizes.
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="3"
android:columnWidth="100dp"
android:stretchMode="columnWidth"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"/>
9) List different types of Views? Explain Scroll View with example
1. Basic Views:
o TextView: Displays text
o EditText: Editable text input field
o Button: Standard clickable button
o ImageView: Displays images
o ImageButton: Button with an image
2. Layout Views (ViewGroups):
o LinearLayout: Arranges views in a single column or row
o RelativeLayout: Positions views in relation to each other
o ConstraintLayout: Flexible positioning with constraints
o FrameLayout: Simple frame for holding a single view
o TableLayout: Arranges views in rows and columns
3. List and Grid Views:
o ListView: Scrollable list of items
o GridView: 2D scrollable grid of items
o RecyclerView: Flexible and efficient list/grid
o ViewPager: Swipeable pages of views
4. Advanced Input Views:
o CheckBox: Two-state button (checked/unchecked)
o RadioButton: Mutually exclusive option button
o Switch: On/off toggle switch
o SeekBar: Slider for selecting values
o RatingBar: Star rating input
5. Date and Time Views:
o DatePicker: Select date
o TimePicker: Select time
o CalendarView: Calendar date selection
6. Specialty Views:
o WebView: Displays web content
o VideoView: Plays video content
o ScrollView: Enables scrolling for content
o HorizontalScrollView: Enables horizontal scrolling
o ProgressBar: Shows progress of operations
o SearchView: Search input field
o SurfaceView: Drawing surface for custom graphics
ScrollView Example:
ScrollView is a ViewGroup that allows vertical scrolling of content that exceeds the
screen height.
It can contain only one direct child (typically a layout that then contains other
views). For horizontal scrolling, use HorizontalScrollView.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scroll View Example"
android:textSize="24sp"
android:layout_gravity="center_horizontal"
android:layout_margin="16dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bottom Button"
android:layout_margin="16dp"/>
</LinearLayout>
</ScrollView>
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
10) Develop an android application to calculate age using date and time picker.
XML file:
JAVA file:
package com.example.progressbar;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
TextView selectedDate, selectedTime, ageResult;
Button selectDateButton, selectTimeButton;
int birthYear;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize UI components
selectedDate = findViewById(R.id.selectedDate);
selectedTime = findViewById(R.id.selectedTime);
ageResult = findViewById(R.id.ageResult);
selectDateButton = findViewById(R.id.selectDateButton);
selectTimeButton = findViewById(R.id.selectTimeButton);
// Select Date
selectDateButton.setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(
MainActivity.this,
(view, selectedYear, selectedMonth, selectedDay) ->
{
birthYear = selectedYear;
selectedDate.setText("Selected Date: " +
selectedDay + "/" + (selectedMonth + 1) + "/" + selectedYear);
calculateAge();
},
year, month, day);
datePickerDialog.show();
});
// Select Time
selectTimeButton.setOnClickListener(v -> {
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(
MainActivity.this,
(view, selectedHour, selectedMinute) ->
selectedTime.setText("Selected Time: " +
selectedHour + ":" + selectedMinute),
hour, minute, true);
timePickerDialog.show();
});
}
// Calculate Age
private void calculateAge() {
if (birthYear == 0) return;
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int age = currentYear - birthYear;
ageResult.setText("Your Age: " + age + " years");
}
}
1. User Notification
Alerts help in notifying users about important events (like errors, warnings,
confirmations).
2. User Decisions
Alerts often provide options like OK / Cancel, helping users to make decisions.
3. Prevent Mistakes
They act as a confirmation step before doing something critical (like deleting
data).
4. Improves UX (User Experience)
Alerts guide users and make the app feel more responsive and interactive.
5. Error Handling
Helps to inform users about problems (like no internet connection or invalid
input).
12) List different methods of Date Picker control view.
XML:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textViewContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="100sp"
android:scrollbars="vertical" />
</LinearLayout>
</ScrollView>
JAVA file:
package com.example.scrollview;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
CHAPTER FIVE
BLOCK DIAGRAM:
Syntax:
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
Explanation:
<intent-filter>: Declares what kind of intents the component can respond to.
<action>: Specifies the action (e.g., MAIN, VIEW, etc.)
<category>: Specifies additional info about the intent (e.g., LAUNCHER, DEFAULT, etc.)
4) Write an intent to display the phone dialer with the given number filled in
XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/a
ndroid"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:gravity="center">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit1"
android:hint="Enter the Phone Number"
android:inputType="phone"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/edit1"
android:layout_centerHorizontal="true"
android:layout_margin="20dp"
android:text="Dial"
android:id="@+id/btn"
/>
</RelativeLayout>
Java file:
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity
{
EditText number;
Button dial;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
number=findViewById(R.id.edit1);
dial=findViewById(R.id.btn);
dial.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,
"Clicked on Dial", Toast.LENGTH_SHORT).show();
Uri
uri=Uri.parse("tel:"+number.getText().toString());
Intent intent=new
Intent(Intent.ACTION_DIAL,uri);
try {
startActivity(intent);
}catch (SecurityException s){
In Android application development, permissions are used to protect user privacy and
control access to sensitive features or data on the device (like camera, contacts, internet,
etc.).
🔐 Types of Permissions in Android:
✅ 1. Normal Permissions
These are permissions that pose very little risk to the user's privacy or security.
Android automatically grants these permissions when the app is installed.
Examples:
ACCESS_NETWORK_STATE – Check if a network is available.
INTERNET – Access the internet.
VIBRATE – Use the phone's vibration.
SET_WALLPAPER – Change the device wallpaper.
✅ 2. Dangerous Permissions
These involve access to the user's private data or control over the device.
Android asks the user to approve these at runtime (from Android 6.0+).
Examples:
READ_CONTACTS – Access the user’s contacts.
ACCESS_FINE_LOCATION – Access precise location.
CAMERA – Use the device camera.
RECORD_AUDIO – Access the microphone.
These permissions are grouped (e.g., CONTACTS, LOCATION, STORAGE) and if the user
grants one, all related ones are usually allowed.
✅ 3. Signature Permissions
Granted only if the requesting app is signed with the same certificate as the app that
declared the permission.
Used mainly by system apps or apps from the same developer.
Example:
A permission defined by a custom service you created that only your own apps can
access.
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.INTERNET"/>
AsyncTask Methods:
AsyncTask is an abstract class that enables proper and easy use of the UI thread by
performing background operations and publishing results on the UI thread.
Key Methods:
1. onPreExecute()
o Runs on UI thread before doInBackground()
o Used for setup (show progress dialog, etc.)
2. doInBackground(Params...)
o Performs computation on background thread
o Must override this method
o Can call publishProgress() to update UI
3. onProgressUpdate(Progress...)
o Runs on UI thread after publishProgress() is called
o Used to update progress indicators
4. onPostExecute(Result)
o Runs on UI thread after background computation finishes
o Receives result from doInBackground()
o Used to update UI with results
5. onCancelled()
o Called when task is cancelled
o Runs on UI thread
Service Methods:
Services are Android components for long-running operations without UI.
Key Service Methods:
1. onCreate()
o Called when service is first created
o Used for one-time setup
2. onStartCommand(Intent, int, int)
o Called for started services with each startService() call
o Contains the work to be done
o Must return one of:
START_NOT_STICKY: Don't recreate if killed
START_STICKY: Recreate but with null intent
START_REDELIVER_INTENT: Recreate with last intent
3. onBind(Intent)
o Called for bound services
o Returns IBinder interface for clients
o Must implement if service allows binding
4. onUnbind(Intent)
o Called when all clients unbind
o Return true if you want onRebind() later
5. onRebind(Intent)
o Called if new clients bind after onUnbind() returned true
6. onDestroy()
o Called when service is being destroyed
o Clean up resources here
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" android:required="true"/>
🖼️ activity_main.xml layout
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/imageView"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_margin="16dp"
android:background="#CCCCCC" />
<Button
android:id="@+id/captureButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Capture Image" />
</LinearLayout>
👨💻 MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
ImageView imageView;
Button captureButton;
static final int CAMERA_REQUEST = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
9) WAP to show the list of the sensors supported by the mobile phone.
XML file:
<?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:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list1"/>
</RelativeLayout>
JAVA file:
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.List;
public class MainActivity extends AppCompatActivity {
SensorManager smm;
List<Sensor> sensor;
ListView l1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
smm=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
l1=findViewById(R.id.list1);
sensor=smm.getSensorList(Sensor.TYPE_ALL);
l1.setAdapter(new ArrayAdapter<Sensor>(this,
android.R.layout.simple_list_item_1,sensor));
}
10) AsyncTask with Limitations
📌 What is AsyncTask?
AsyncTask is a class in Android used to perform background tasks (like downloading,
database operations, etc.) without blocking the main UI thread.
It has 3 main parts:
1. doInBackground() → runs in the background (slow work)
2. onPreExecute() → runs before the task starts
3. onPostExecute() → runs after the task completes (usually to update UI)
❌ Not lifecycle-aware
If the user rotates the screen or activity is destroyed, AsyncTask continues in the
background and may crash your app when it tries to update the UI.
⏱️ Memory leaks
If not handled properly, it may keep a reference to the activity, causing memory leaks.
🚫 Deprecated in Android 11
Google recommends using ViewModel + LiveData or Kotlin Coroutines now, because
AsyncTask is outdated.
💅✍ No Error Handling
Must manually catch the exceptions.
11) Service Lifecycle with Diagram
1. Started Service
2. Bound Service
This service is started using startService(). It runs in the background even if the activity that
started it is closed.
🔄 Lifecycle Steps:
1. Call to startService()
➤ This is the first step. The service is requested to start by some component like an
Activity.
➤ The system then creates the service if it is not already running.
2. onCreate()
➤ This method is called only once when the service is created for the first time.
➤ It is used to initialize things like setting up resources or variables.
3. onStartCommand()
➤ Called every time startService() is called.
➤ This is where you write the actual background task like downloading a file, playing
music, etc.
➤ The service now enters the "active running state".
4. Service Running
➤ The service will keep running in the background, doing its job.
➤ It does not stop on its own unless you stop it manually using stopSelf() (inside the
service) or stopService() (from outside like activity).
5. onDestroy()
➤ When the service is stopped, this method is called.
➤ It is used to clean up memory, stop threads, or close resources.
6. Service Shut Down
➤ Now the service is completely destroyed and removed from memory.
➤ This is the end of the lifecycle for a started service.
This service is bound using bindService(). It allows a component (like an Activity) to connect to
the service and interact with it directly.
🔄 Lifecycle Steps:
1. Call to bindService()
➤ The client (like an Activity) requests to bind/connect to the service.
➤ This is used when you want the service to return data or allow communication (e.g.,
get sensor data).
2. onCreate()
➤ Called once when the service is created.
➤ Used to initialize things before binding starts.
3. onBind()
➤ This is called after onCreate().
➤ Returns an IBinder object to allow communication between the service and the
client.
➤ This allows your activity to call methods inside the service.
4. Clients are Bound to Service
➤ The service is now active and can be used by the client to perform operations.
➤ It stays active only while the client is connected.
5. onUnbind()
➤ This is called when the client disconnects from the service using unbindService().
➤ It is a signal that the client no longer needs the service.
6. onDestroy()
➤ Called when there are no more clients, and the service is ready to shut down.
➤ Used to clean up everything before shutting down the service.
7. Service Shut Down
➤ The service is now completely stopped and removed from memory.
2. onAttach()
This method is called first.
It means the fragment is now attached to its host activity.
You can get the context of the activity here.
Useful for performing tasks that need to access the activity.
3. onCreate()
This method is called to initialize fragment logic, such as variables or retained data.
This is where you perform non-UI initializations.
It is similar to the onCreate() method in activities.
4. onCreateView()
This method is responsible for creating and returning the view hierarchy (UI) of the
fragment.
Here, you inflate the fragment layout XML file using a layout inflater.
5. onActivityCreated()
This is called after the activity's onCreate() method has completed.
It indicates that the activity and fragment UI are fully created.
You can now interact with the activity’s views.
6. onStart()
This method is called when the fragment becomes visible to the user.
At this stage, the fragment is not yet active or interacting with the user.
7. onResume()
This is called when the fragment becomes fully active and ready for user interaction.
This is the point where the fragment is visible and interactive.
At this stage, the fragment is considered active.
8. Fragment is Active
The fragment remains in this state while the user interacts with it or until it is paused
or removed.
9. onPause()
This method is called when the fragment is no longer in the foreground but is still
visible.
This typically occurs when another fragment or activity comes in front of it.
You can pause animations or ongoing tasks here.
10. onStop()
Called when the fragment is completely hidden.
The fragment is no longer visible to the user.
11. onDestroyView()
Called when the view hierarchy of the fragment is removed.
This is where you clean up resources related to the view.
12. onDestroy()
Called when the fragment is about to be completely destroyed from memory.
You can use this to clean up any remaining non-UI data or resources.
13. onDetach()
The final method called in the lifecycle.
This indicates the fragment is no longer associated with the activity.
It has been fully removed.
Fragment is Destroyed
After onDetach(), the fragment object is destroyed and is no longer in memory.
To access Bluetooth devices in an Android app, you must define the necessary Bluetooth
permissions in the AndroidManifest.xml file. These permissions allow your app to connect,
communicate, and scan Bluetooth devices.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</LinearLayout>
JAVA:
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate Invoked", Toast.LENGTH_SHORT).show();
}
@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume Invoked", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "onPause Invoked", Toast.LENGTH_SHORT).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "onStop Invoked", Toast.LENGTH_SHORT).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "onRestart Invoked", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "onDestroy Invoked", Toast.LENGTH_SHORT).show();
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="BLUETOOTH"
android:textSize="20sp"
android:layout_marginBottom="20dp"/>
<Button
android:id="@+id/btnOn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn On"/>
<Button
android:id="@+id/btnVisible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Visible"
android:layout_marginTop="10dp"/>
<Button
android:id="@+id/btnList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:layout_marginTop="10dp"/>
<Button
android:id="@+id/btnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off"
android:layout_marginTop="10dp"/>
</LinearLayout>
JAVA:
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Set;
BluetoothAdapter bluetoothAdapter;
Button btnOn, btnVisible, btnList, btnOff;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = findViewById(R.id.btnOn);
btnVisible = findViewById(R.id.btnVisible);
btnList = findViewById(R.id.btnList);
btnOff = findViewById(R.id.btnOff);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btnOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!bluetoothAdapter.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(turnOn);
Toast.makeText(getApplicationContext(), "Bluetooth Turned On",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Bluetooth Already On",
Toast.LENGTH_SHORT).show();
}
}
});
btnVisible.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent getVisible = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(getVisible);
}
});
btnList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : devices) {
Toast.makeText(getApplicationContext(), device.getName(),
Toast.LENGTH_SHORT).show();
}
}
});
btnOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bluetoothAdapter.disable();
Toast.makeText(getApplicationContext(), "Bluetooth Turned Off",
Toast.LENGTH_SHORT).show();
}
});
}
}
JAVA:
package com.example.smsapp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
number = findViewById(R.id.number);
message = findViewById(R.id.message);
sendBtn = findViewById(R.id.sendBtn);
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS}, 1);
sendBtn.setOnClickListener(v -> {
String num = number.getText().toString();
String msg = message.getText().toString();
SmsManager.getDefault().sendTextMessage(num, null, msg, null, null);
Toast.makeText(this, "SMS Sent", Toast.LENGTH_SHORT).show();
});
}
}
M@nifest file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsapp">
<application
android:allowBackup="true"
android:theme="@style/Theme.SMSApp">
<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>
2) List different methods which we can use with Location object to get location.
These methods allow developers to access various aspects of location data for navigation,
mapping, and location-based services.
Google Maps API offers several types of maps that can be used in Android applications:
1. Normal Map (MAP_TYPE_NORMAL): Standard road map showing roads, some man-
made features, and important natural features
2. Satellite Map (MAP_TYPE_SATELLITE): Photographic map from satellite imagery
3. Hybrid Map (MAP_TYPE_HYBRID): Combines satellite imagery with a transparent layer
of major streets and place labels
4. Terrain Map (MAP_TYPE_TERRAIN): Shows terrain and vegetation information along
with roads and labels
5. None (MAP_TYPE_NONE): No map tiles are displayed, used when you want to display
custom map tiles
Each of these map types serves different purposes and can be set using the setMapType()
method of the GoogleMap object.
2. zoomIn()
Increases the current zoom level by one unit.
Offers a programmatic way to zoom in.
3. zoomOut()
Decreases the current zoom level by one unit.
Used to zoom out from the current map position.
4. getZoomLevel()
Returns the current zoom level of the map as a float value.
Useful for retrieving the map's zoom state.
5. setOnZoomInClickListener(View.OnClickListener listener)
Attaches a click listener to the Zoom In button.
Triggered when the user taps Zoom In.
6. setOnZoomOutClickListener(View.OnClickListener listener)
Attaches a click listener to the Zoom Out button.
Triggered when the user taps Zoom Out.
7. setZoomControlsEnabled(boolean enabled)
Enables or disables the display of built-in zoom controls (UI buttons).
Commonly used in GoogleMap object to control UI visibility.
8. setZoomGesturesEnabled(boolean enabled)
Enables or disables pinch-to-zoom gestures.
When disabled, users cannot zoom the map using finger gestures.
9. getMinZoomLevel()
Returns the minimum zoom level allowed for the map.
Defines how far out the user can zoom.
10. getMaxZoomLevel()
Returns the maximum zoom level allowed for the map.
Defines how far in the user can zoom.
13. moveCamera(CameraUpdateFactory.zoomTo(float))
Instantly sets the map's zoom to a specified level without animation.
14. moveCamera(CameraUpdateFactory.zoomIn())
Instantly zooms the map in by one zoom level.
15. moveCamera(CameraUpdateFactory.zoomOut())
Instantly zooms the map out by one zoom level.
16. animateCamera(CameraUpdateFactory.zoomBy(float))
Animates the map's zoom by a specified number of zoom levels.
Positive values zoom in; negative values zoom out.
17. animateCamera(CameraUpdateFactory.zoomTo(float))
Smoothly animates to a specific zoom level.
The Android Security model is a multi-layered approach designed to protect users, their data,
and the system itself:
1. Application Sandbox:
o Each Android application runs in its own isolated environment (sandbox)
o Applications cannot access each other's data or code unless explicitly
permitted
o Based on Linux user ID isolation, with each app assigned a unique UID
2. Permission System:
o Controls access to sensitive device features and user data
o Applications must request permissions to access protected functionality
o Runtime permissions (introduced in Android 6.0) require user approval at
runtime
o Permissions are categorized into normal, signature, and dangerous groups
3. Application Signing:
o All Android applications must be digitally signed with a developer's certificate
o Ensures application authenticity and establishes a trust relationship
o Enables update verification from the same developer
4. SELinux (Security-Enhanced Linux):
o Mandatory Access Control system that further restricts application capabilities
o Limits damage potential of compromised applications
o Enforces system-wide security policies
5. Verified Boot:
o Ensures the operating system hasn't been tampered with
o Checks integrity of the entire system from bootloader to system image
6. Full-Disk Encryption and File-Based Encryption:
o Protects data at rest by encrypting device storage
o Ensures data cannot be accessed without proper authentication
7. Secure IPC (Inter-Process Communication):
o System services and applications communicate through well-defined
interfaces
o Intent-based communication between components follows security rules
8. Network Security:
o Network Security Configuration for controlling network traffic
o HTTPS by default for network connections
o Certificate pinning options to prevent man-in-the-middle attacks
9. Biometric Authentication:
o Fingerprint, facial recognition, and other biometric authentication methods
o Protected by secure hardware when available
10. Google Play Protect:
o Scans applications for security issues
o Monitors for potentially harmful applications
o Provides security updates through Google Play Services
The Android Security model is continuously evolving with each new Android version, adding
additional layers of protection while maintaining backward compatibility.
7) Discuss Developer Console with its purpose
The Google Play Developer Console (now called Google Play Console) is a web-based
platform that allows Android developers to publish and manage their applications on the
Google Play Store. Its key purposes and features include:
The Google Play Console serves as the central hub for an Android developer's relationship
with Google Play, providing the tools needed to successfully publish, monitor, and grow their
applications in the Android ecosystem.
To become an Android application publisher, you need to complete several important tasks:
Following these steps will help ensure a smooth process for becoming an Android application
publisher on Google Play. The process requires attention to detail, particularly regarding
Google's policies and guidelines, which are continually updated to maintain the quality and
security of the Play Store ecosystem.
Geocoding and Reverse Geocoding are essential concepts in location-based services that
involve converting between human-readable addresses and geographic coordinates.
Reverse Geocoding is the opposite process - converting geographic coordinates (latitude and
longitude) into a human-readable address. This enables applications to: