0% found this document useful (0 votes)
22 views32 pages

Mad QB Ans

The document provides an overview of various UI components in Android, including ImageButton, ToggleButton, ImageView, RadioButton, ScrollView, and ProgressBar, along with their attributes and example code. It explains how to implement these components in XML and Java, detailing methods and usage scenarios. Additionally, it discusses the significance of alerts in enhancing user experience and provides sample code for displaying text in a ScrollView.

Uploaded by

saeedarwatkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views32 pages

Mad QB Ans

The document provides an overview of various UI components in Android, including ImageButton, ToggleButton, ImageView, RadioButton, ScrollView, and ProgressBar, along with their attributes and example code. It explains how to implement these components in XML and Java, detailing methods and usage scenarios. Additionally, it discusses the significance of alerts in enhancing user experience and provides sample code for displaying text in a ScrollView.

Uploaded by

saeedarwatkar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 32

1) Explain Image Button with its attributes.

What is ImageButton?

An ImageButton is a button that displays an image instead of text. It functions like a regular Button but uses an icon or
picture for user interaction.

Example XML Code:


<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"
android:background="@android:color/transparent"
android:contentDescription="Click Me"/>

Common Attributes of ImageButton

 android:src – Sets the image for the button.


 android:background – Defines the button's background
 android:contentDescription – Provides a description for accessibility.
 android:tint – Changes the color of the image inside the button.
 android:scaleType – Controls how the image fits inside the button (fitCenter, centerCrop, etc.).
 android:padding – Adds space inside the button around the image.

2) Write a program to create a toggle button to display ON/OFF


Bluetooth on the display screen.
Xml file:

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">

<ToggleButton
android:id="@+id/tg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON" />
</LinearLayout>

Java File:

package com.example.myapplication;
import android.os.Bundle;
import android.widget.ToggleButton;
import android.widget.Toast;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import android.bluetooth.BluetoothAdapter;

public class MainActivity extends AppCompatActivity


{
ToggleButton tg;
BluetoothAdapter ba;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tg=findViewById(R.id.tg);
ba=BluetoothAdapter.getDefaultAdapter();

tg.setChecked(ba.isEnabled());

tg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(tg.isChecked())
{
ba.enable();
Toast.makeText(MainActivity.this,"Bluetooth is on",
Toast.LENGTH_LONG).show();
}
else {
ba.disable();
Toast.makeText(MainActivity.this,"Bluetooth is off",
Toast.LENGTH_LONG).show();
}
}
});
}
}

3) Explain Image View with its attributes.


Steps to Add an Image in Android Studio:

Copy Image to res/drawable

Right-click res > drawable → Paste Image

Rename it (use lowercase, no spaces).

Use in XML:

<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_image"/>

Use in Java/Kotlin:

imageView.setImageResource(R.drawable.my_image);
imageView.setImageResource(R.drawable.my_image)
For large images, use res/raw or assets.

4) List different methods of Radio Button.


Methods of RadioButton in Android

 RadioButton(Context context)
 RadioButton(Context context, AttributeSet attrs)

 setChecked(boolean checked)
 isChecked()
 toggle()

 setText(CharSequence text)
 getText()

 setTextColor(int color)
 setEnabled(boolean enabled)

5) RadioButton
Xml file:

<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">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Single Radio Button"
android:textStyle="bold"/>

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button 1"/>

<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio Button 2"/>

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Radio button inside RadioGroup"
android:textStyle="bold"
android:layout_marginTop="10dp"/>

<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Male"/>

<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Female"/>
</RadioGroup>

<Button
android:id="@+id/buttonShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SHOW SELECTED"
android:layout_marginTop="10dp"/>
</LinearLayout>

Java File

package com.example.myapplication;
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, radioMale, radioFemale;
RadioGroup radioGroup;
Button buttonShow;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

radioButton1 = findViewById(R.id.radioButton1);
radioButton2 = findViewById(R.id.radioButton2);
radioMale = findViewById(R.id.radioMale);
radioFemale = findViewById(R.id.radioFemale);
radioGroup = findViewById(R.id.radioGroup);
buttonShow = findViewById(R.id.buttonShow);

buttonShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String selected = "";

if (radioButton1.isChecked()) {
selected += "Radio Button 1\n";
}
if (radioButton2.isChecked()) {
selected += "Radio Button 2\n";
}
if (radioMale.isChecked()) {
selected += "Male\n";
}
if (radioFemale.isChecked()) {
selected += "Female\n";
}

if (selected.isEmpty()) {
selected = "No selection";
}

Toast.makeText(MainActivity.this, selected, Toast.LENGTH_LONG).show();


}
});
}
}

6) Circular Progress Bar

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">

<ProgressBar
android:id="@+id/circularProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"/>

</LinearLayout>

Java File:
package com.example.myapplication;

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);
}
}

7) Attributes of ImageView
Important Attribute:

 android:src – Sets the image resource.


 android:scaleType – Defines how the image fits inside the view.
 android:contentDescription – Provides accessibility support.
 android:adjustViewBounds – Resizes the image while maintaining aspect ratio.
 android:layout_width and android:layout_height – Define the size of the ImageView.

8) Describe android:strechMode of GridView in detail.


android:stretchMode in Android

Definition:

The android:stretchMode attribute is used in GridView to define how columns should expand to fill the available space.

Usage:

It is set in the XML layout file within the <GridView> tag.

<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"/>

Available Values & Their Effects:

1. none (Default)
o No columns are stretched.
o The column width remains fixed.
2. spacingWidth
o Extra space is distributed as padding between columns.
o Column width remains the same.
3. columnWidth
o Extra space is added to the columns, making them wider.
o Best when using numColumns="auto_fit" to adjust dynamically.
4. spacingWidthUniform (API Level 26+)
o Like spacingWidth, but ensures equal spacing across all columns.

When to Use:

 Use columnWidth if you want columns to resize dynamically.


 Use spacingWidth if you want consistent spacing without changing column size.

9) ScrollView
ScrollView is a view group used to make content scrollable when it doesn’t fit on the screen. It supports vertical
scrolling by default, while HorizontalScrollView enables horizontal scrolling. It is commonly used for long forms, large
text content, or images. Since it can have only one direct child, use a LinearLayout to arrange multiple views inside it.
ScrollView ensures smooth scrolling for a better user experience.

Attributes:
android:layout_width – Sets the width of the ScrollView (e.g., match_parent, wrap_content).
android:layout_height – Defines the height of the ScrollView (match_parent allows full-screen scrolling).
android:fillViewport – If set to true, forces child views to expand and fill the viewport.
android:background – Sets the background color or drawable of the ScrollView.
android:scrollbars – Controls scrollbar visibility (vertical, horizontal, or none).
android:fadingEdgeLength – Defines the size of the fading effect when scrolling.
android:overScrollMode – Controls the overscroll effect (always, ifContentScrolls, never).

For Example:

<?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:background="@android:color/white">

<ScrollView
android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView

android:id="@+id/scrolltext"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:textSize="24sp"

android:text="This is a sample scrollable text. Add more lines here to test scrolling."

android:textColor="@android:color/holo_green_dark"/>

</ScrollView>

</LinearLayout>

10) Methods of Date Picker


Important Methods of DatePicker

1. getYear() – Returns the selected year.


2. getMonth() – Returns the selected month (0-based index).
3. getDayOfMonth() – Returns the selected day.
4. setMinDate(long date) – Sets the minimum date selection.
5. setMaxDate(long date) – Sets the maximum date selection.
6. getFirstDayOfWeek() – Returns the first day of the week in the current locale.

11) Methods of Progress Bar


Methods of ProgressBar in Android

 setProgress(int value) – Sets the current progress.


 getProgress() – Gets the current progress value.
 incrementProgressBy(int diff) – Increases progress by a given value.
 setMax(int maxValue) – Sets the maximum progress value.
 getMax() – Gets the maximum progress value.

 setIndeterminate(boolean indeterminate) – Enables/disables indeterminate mode.


 isIndeterminate() – Checks if progress is indeterminate.
12) Significance of displaying alerts in android.
1. User Notification:

 Alerts provide a quick and clear notification to the user about important actions or information, such as errors,
warnings, or confirmations.
 Example: Showing a warning when the user tries to exit an unsaved form.

2. Feedback on Actions:

 Alerts are used to give immediate feedback on a user's actions (e.g., successful submission or failure to
complete an action).
 Example: A success message after a successful login.

3. Direct User Interaction:

 Alerts prompt user decisions by presenting buttons for confirmation, like "OK," "Cancel," or "Yes/No."
 Example: Asking users to confirm before deleting a file.

4. Improve UX:

 They help improve user experience by guiding users and keeping them informed about the app's state, ensuring
they don't miss important information.
 Example: Informing users of network issues when the app cannot fetch data.

5. Error Handling:

 Alerts are important for handling errors gracefully by informing the user and often providing options to correct
or report the issue.
 Example: Displaying an error when an incorrect input is provided (e.g., invalid email format).

13) Write a program to display a text View using scroll View.


XML file:

<?xml version="1.0" encoding="utf-8"?>


<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:text="Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Pellentesque euismod, nisi eu consectetur convallis, nunc risus ultrices
orci, sed vehicula erat purus nec quam. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia curae; Integer tincidunt,
justo vel consectetur tempus, libero lorem ultricies nunc, eget faucibus
velit neque a felis. \n\n
(Add more text here to make it scrollable...)"
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;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
}
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="wrap_content"
android:orientation="vertical"
android:padding="24dp"
android:gravity="center_horizontal">

<!-- Button to select date -->


<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Date"
android:layout_marginTop="20dp" />

<!-- TextView to display selected date -->


<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Date:"
android:layout_marginTop="10dp" />

<!-- Button to select time -->


<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select Time"
android:layout_marginTop="20dp" />

<!-- TextView to display selected time -->


<TextView
android:id="@+id/txt2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Time:"
android:layout_marginTop="10dp" />

<!-- TextView to show calculated age -->


<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your Age:"
android:textSize="16sp"
android:layout_marginTop="20dp"
android:textStyle="bold" />
</LinearLayout>

Java :

package com.example.myapplication;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

TextView txt1, txt2, txtage;


Button btn1, btn2;
int birthYear;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

txt1 = findViewById(R.id.txt1);
txt2 = findViewById(R.id.txt2);
txtage = findViewById(R.id.age);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);

btn1.setOnClickListener(v -> {
Calendar c = Calendar.getInstance();
int y = c.get(Calendar.YEAR);
int m = c.get(Calendar.MONTH);
int d = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog dp = new DatePickerDialog(this, (view, year, month, day) -> {


birthYear = year;
txt1.setText("Selected Date: " + day + "/" + (month + 1) + "/" + year);
calculateAge();
}, y, m, d);
dp.show();
});

btn2.setOnClickListener(v -> {
Calendar c = Calendar.getInstance();
int h = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);

TimePickerDialog tp = new TimePickerDialog(this, (view, hour, minute) -> {


txt2.setText("Selected Time: " + hour + ":" + minute);
}, h, min, true);
tp.show();
});
}

private void calculateAge() {


int currentYear = Calendar.getInstance().get(Calendar.YEAR);
int age = currentYear - birthYear;
txtage.setText("Your Age: " + age + " years");
}
}

1. Syntax of Intent-Filter.
Syntax:

<intent-filter

android:icon="drawable resource"

android:label="string resource"

android:priority="integer" >

...

</intent-filter>

2. Activity Lifecycle
1. onCreate() – This method runs when the activity starts for the first time. It is used to set up the screen layout
and initialize variables. This is where you create buttons, text fields, and other UI components. It runs only once
when the activity is created.
2. onStart() – This method runs when the activity becomes visible to the user. It is called after onCreate(), or when
returning to the activity from the background. At this stage, the user can see the activity, but it might not yet be
interactive.
3. onResume() – This method runs when the activity is fully visible and the user can interact with it. This is where
animations, media playback, or sensors should start running. If the app was paused, this method restarts those
processes.
4. onPause() – This method runs when the activity is partially hidden (e.g., a pop-up appears). It is used to pause
the things like music or animations to save battery and performance. The activity is still in memory but not fully
active.
5. onStop() – This method runs when the activity is no longer visible on the screen. The system may remove it from
memory if needed. It is used to stop heavy operations like network calls or database access.
6. onRestart() – This method runs when an activity is coming back from the stopped state. It is used to refresh the
UI or reload data before making it visible again. After this, onStart() and onResume() will be called.
7. onDestroy() – This method runs just before the activity is completely removed from memory. It is used to free
up resources, close database connections, or save final data. The activity cannot be restarted after this without
creating a new one.

3. Write intent to display the phone dialer with the given


number filled in.
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"
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:

package com.example.myapplication;
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);
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) {
Uri uri=Uri.parse("tel:"+number.getText().toString());

Intent intent=new Intent(Intent.ACTION_DIAL,uri);


startActivity(intent);
}
});

}
}

4. Explain Database packages which are necessary in SQLite.


1. android.database.sqlite

This package is essential for managing SQLite databases in Android. It provides classes like SQLiteDatabase for
executing SQL queries and SQLiteOpenHelper for handling database creation and upgrades. Another important
class is SQLiteQueryBuilder, which simplifies query building. These classes help in performing operations like
insert, update, delete, and retrieve data from the database efficiently.

2. android.database

This package contains general database-related classes and interfaces used for handling data retrieval and
manipulation. The Cursor class is the most important, as it allows reading and navigating through query results.
Another useful class is DatabaseUtils, which provides utility methods for working with databases. It helps
simplify operations like converting cursor data to strings or counting rows in a table.

3. android.content

This package is indirectly required for database operations, as it provides essential utilities for managing data.
The ContentValues class is used to store values before inserting or updating records in the database. The Context
class is crucial because it helps access and manage database files. Without these, working with SQLite
databases in Android would be difficult.

5. Describe different types of permissions used while developing


android application.
Android applications utilize three main types of permissions: install-time, runtime, and special permissions, each
impacting how your app accesses sensitive data or performs restricted actions.

Here's a breakdown:

1. Install-time Permissions:

 These permissions are declared in the AndroidManifest.xml file and are granted to the app during installation.
 Examples include INTERNET, READ_EXTERNAL_STORAGE, and WRITE_EXTERNAL_STORAGE.
 The system automatically grants these permissions, and the user doesn't need to explicitly grant them during
runtime.

2. Runtime Permissions:

 These permissions require user confirmation at runtime, meaning the app must request them from the user
during app execution.
 Examples include permissions related to location (ACCESS_FINE_LOCATION), camera (CAMERA), and
microphone (RECORD_AUDIO).
 The user can choose to grant or deny these permissions, and the app can only access the corresponding
functionality if the permission is granted.

3. Special Permissions:
 These permissions guard access to system resources that are particularly sensitive or not directly related to user
privacy.
 Examples include permissions like scheduling exact alarms, displaying over other apps, and accessing all storage
data.
 Special permissions are different from install-time and runtime permissions and require specific handling and
may be managed through system settings.

6. List basic methods used in AsyncTask and Service in android.


Basic Methods of AsyncTask and Service in Android

1. AsyncTask Methods

 onPreExecute() – Runs before the task starts (UI thread).


 doInBackground(Params... params) – Runs in the background (worker thread).
 onProgressUpdate(Progress... values) – Updates UI during execution.
 onPostExecute(Result result) – Runs after the task completes (UI thread).
 onCancelled() – Called if the task is canceled before completion.

2. Service Methods

 onCreate() – Called when the service is first created.


 onStartCommand(Intent intent, int flags, int startId) – Handles each service start request.
 onBind(Intent intent) – Returns an IBinder for bound services.
 onUnbind(Intent intent) – Called when all clients disconnect.
 onDestroy() – Called when the service is stopped.

7. Explain Async Task with limitations.


Understanding AsyncTask in Android

What is AsyncTask?

AsyncTask is an Android class used to perform background operations and update the UI without blocking the main
thread.

Lifecycle & Methods:

1. onPreExecute() – Runs on the UI thread before execution (used for setup).


2. doInBackground(Params... params) – Runs in the background thread (for heavy tasks).
3. onProgressUpdate(Progress... values) – Updates progress in the UI thread.
4. onPostExecute(Result result) – Runs on the UI thread after execution.
5. onCancelled() – Called if the task is canceled.
Example:
private class MyTask extends AsyncTask<Void, Integer, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}

@Override
protected String doInBackground(Void... voids) {
return "Task Completed";
}

@Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}

Limitations of AsyncTask

1. Not Suitable for Long Tasks – Designed for short background tasks; long tasks may cause memory leaks.
2. Memory Leaks – If the AsyncTask holds a reference to an Activity, it may leak memory when the activity is
destroyed.
3. Limited Parallel Execution – Runs tasks sequentially (before API 11); after API 11, executeOnExecutor() is
needed for parallel execution.
4. No Proper Lifecycle Awareness – Cannot detect when an Activity is destroyed, leading to UI updates after it's
gone.
5. Deprecation in API 30 – Android has deprecated AsyncTask in favor of Executors and WorkManager.

8. Service lifecycle
1. Started

a. A service is started when an application component, such as an activity, starts it by calling startService().

b. Now the service can run in the background indefinitely, even if the component that started is destroyed.

2. Bound

a. A service is bound when an application component binds to it by calling bindService().

b. A bound service offers a client-server interface that allows components to interact with the service, send requests, get
results, and even do so across processes with Inter Process Communication (IPC).

c. Like any other components service also has callback methods. These will be invoked while the service is running to
inform the application of its state. Implementing these in our custom service would help you in performing the right
operation in the right state.

d. There is always only a single instance of service running in the app. If you are calling startService() for a single service
multiple times in our application it just invokes the onStartCommand() on that service. Neither is the service restarted
multiple times nor are its multiple instances created.

1. onCreate(): This is the first callback which will be invoked when any component starts the service. If the same service
is called again while it is still running this method won’t be invoked. Ideally one time setup and initialization should be
done in this callback.

2. onStartCommand() /startSetvice(): This callback is invoked when service is started by any component by calling
startService(). It basically indicates that the service has started and can now run indefinitely.
3. onBind(): To provide binding for a service, you must implement the onBind() callback method. This method returns an
IBinder object that defines the programming interface that clients can use to interact with the service.

4. onUnbind(): This is invoked when all the clients are disconnected from the service.

5. onRebind(): This is invoked when new clients are connected to the service. It is called after onRebind

6. onDestroy(): This is a final clean up call from the system. This is invoked just before the service is being destroyed.

9. How to define Bluetooth permissions to access Bluetooth


device.
To access Bluetooth devices in an Android app, you need to define Bluetooth permissions in the
AndroidManifest.xml file.

1. Add Basic Bluetooth Permissions

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

 BLUETOOTH → Allows connecting to Bluetooth devices.


 BLUETOOTH_ADMIN → Allows scanning and pairing with devices.

2. For Android 12 (API 31+)

Starting from Android 12, additional runtime permissions are required:

<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>

 BLUETOOTH_SCAN → Required for searching nearby devices.


 BLUETOOTH_CONNECT → Required for connecting to paired devices.

10. WAP to create a Hello World activity using all lifecycle


methods to display message of activity process.

Xml file:

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/main"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Activity Lifecycle..."

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Java file:

package com.example.saee_17;

import android.os.Bundle;

import android.widget.Toast;

import androidx.activity.EdgeToEdge;

import androidx.annotation.NonNull;

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 {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

EdgeToEdge.enable(this);

setContentView(R.layout.activity_main);

Toast.makeText(this, "onCreate() method called...", Toast.LENGTH_LONG).show();

@Override

protected void onResume(){

super.onResume();

Toast.makeText(this, "onResume() method called...", Toast.LENGTH_LONG).show();

@Override

protected void onPause()

super.onPause();

Toast.makeText(this, "onPause() method called...", Toast.LENGTH_LONG).show();

@Override

protected void onStop()

super.onStop();

Toast.makeText(this, "onStart() method called...", Toast.LENGTH_LONG).show();

@Override
protected void onRestart()

super.onRestart();

Toast.makeText(this, "onRestart() method called...", Toast.LENGTH_LONG).show();

@Override

protected void onDestroy()

super.onDestroy();

Toast.makeText(this, "onDestroy() method called...", Toast.LENGTH_LONG).show();

11. WAP to turn on, get visible, list device and turn off
Bluetooth with the help of GUI.
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">

<TextView
android:text="BLUETOOTH"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:layout_marginBottom="10dp"/>

<Button
android:id="@+id/btnTurnOn"
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"/>

<Button
android:id="@+id/btnListDevices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"/>

<Button
android:id="@+id/btnTurnOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn Off"/>
</LinearLayout>

Java file:

package com.example.myapplication;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Set;

public class MainActivity extends AppCompatActivity {


BluetoothAdapter bluetoothAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Button btnTurnOn = findViewById(R.id.btnTurnOn);
Button btnVisible = findViewById(R.id.btnVisible);
Button btnListDevices = findViewById(R.id.btnListDevices);
Button btnTurnOff = findViewById(R.id.btnTurnOff);

// Turn On Bluetooth
btnTurnOn.setOnClickListener(v -> {
if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) {
startActivity(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE));
Toast.makeText(this, "Turning On Bluetooth", Toast.LENGTH_LONG).show();
}
});

// Make Device Visible


btnVisible.setOnClickListener(v -> {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(intent);
Toast.makeText(this, "Device is Visible", Toast.LENGTH_LONG).show();
});

// List Paired Devices


btnListDevices.setOnClickListener(v -> {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
StringBuilder devices = new StringBuilder("Paired Devices:\n");
for (BluetoothDevice device : pairedDevices) {
devices.append(device.getName()).append(" -
").append(device.getAddress()).append("\n");
}
Toast.makeText(this, devices.toString(), Toast.LENGTH_LONG).show();
});

// Turn Off Bluetooth


btnTurnOff.setOnClickListener(v -> {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(this, "Bluetooth Turned Off", Toast.LENGTH_LONG).show();
}
});
}
}

Permissions

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
<uses-permission android:name="android.permission.BLUETOOTH_SCAN"/>

12. WAP to display the list of sensors supported by the


mobile device.
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:padding="20dp">

<TextView
android:text="Available Sensors: "
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:textSize="20sp"
android:textStyle="bold"
android:id="@+id/txt"
/>

</LinearLayout>

Java File:

package com.example.myapplication;

import android.annotation.SuppressLint;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import java.util.List;

public class MainActivity extends AppCompatActivity{


TextView txt;
SensorManager sm;
@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt=findViewById(R.id.txt);
sm=(SensorManager)getSystemService(SENSOR_SERVICE);
List<Sensor> sensors=sm.getSensorList(Sensor.TYPE_ALL);
StringBuilder name=new StringBuilder();

int i;
for(i=0;i<sensors.size();i++)
{
name.append(sensors.get(i).getName()).append("/n");
}
txt.setText(name.toString());
}

I) List different methods which we can use with location


object to get location based information
1. getLatitude() – Returns the latitude in degrees.
2. getLongitude() – Returns the longitude in degrees.
3. getAltitude() – Returns the altitude in meters.
4. getSpeed() – Returns the speed in meters/second.
5. getAccuracy() – Returns the accuracy in meters.
6. hasSpeed() – Returns true if speed is available.

II) List different types of google maps


list of different types of Google Maps:

1. MAP_TYPE_NORMAL
2. MAP_TYPE_SATELLITE
3. MAP_TYPE_TERRAIN
4. MAP_TYPE_HYBRID
5. MAP_TYPE_NONE

III) Explain different methods of google map


1. setMapType(int type)

This method sets the style of the map such as normal, satellite, or terrain. It helps in displaying the map based on your
app's need. You can choose from several predefined map types.
Example:

googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);

2. addMarker(MarkerOptions options)

Adds a marker to the map at a specific latitude and longitude. Markers help show places like cities, stores, or user clicks.
You can also add a title to the marker.
Example:

googleMap.addMarker(new MarkerOptions().position(new LatLng(19.0760, 72.8777)).title("Mumbai"));

3. moveCamera(CameraUpdate update)

Moves the camera to a new position on the map instantly. It is used when you want to show a certain location. No
animation is applied.
Example:

googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(28.6139, 77.2090), 10));

4. animateCamera(CameraUpdate update)

Moves the camera to a new location with animation. It gives a smooth zoom or scroll effect. Useful for a better user
experience.
Example:

googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(12.9716, 77.5946), 12));

6. clear()

Removes all markers, lines, and shapes from the map. It resets the map to an empty view. Useful when updating
location data.
Example:

googleMap.clear();
IV) Explain methods of zoom control

1. hide()

Hides a ZoomControls widget from the screen. Useful when you want to remove zoom controls manually.
Example:

zoomControls.hide();

2. show()

Shows the ZoomControls widget on the screen. Used when you want to display zoom buttons.
Example:

zoomControls.show();

3. setOnZoomInClickListener(View.OnClickListener listener)

Called when the Zoom In button is clicked. You define what happens when zoom in is pressed.
Example:

zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
googleMap.animateCamera(CameraUpdateFactory.zoomIn());
}
});

4. setOnZoomOutClickListener(View.OnClickListener listener)

Called when the Zoom Out button is clicked. You define what happens when zoom out is pressed.
Example:

zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
googleMap.animateCamera(CameraUpdateFactory.zoomOut());
}
});

V) Explain Developer console.


 Google Play Developer Console is the platform that Google provides for Google Play and Android developers to
publish their apps.
 The Google Play Developer console allows app developers and marketers to better understand how their apps
are performing in terms of growth, technical performance such as crashes or display issues, and financials.
 The console offers acquisition reports and detailed analysis which can help app developers to find out how well
an app is really performing.
 The platform is important as it provides developers with access to first party data (trustworthy information
collected about an app’s audience that comes straight from Google Play) that highlights the real performance of
an app.
 It shows the number of impressions an app listing receives and the number of Installs an app receives from
different sources over time

VI) Explain Android Security model


The Android security model is designed to provide a safe and secure environment for mobile applications users by
leveraging a combination of sandboxing, permissions, and application signing. This model helps protect user privacy and
data, as well as maintain the integrity and security of the Android device.

Here is an elaboration on the key aspects of the Android security model:

1. Sandboxing: Application sandboxing means each application runs independently, without access to data from
other applications until permission is granted.
2. Application Signing: Every Android app is signed with a certificate, which uniquely identifies the app and its
developer. The signing certificate allows the system and other apps to verify the authenticity and origin of the
app.
3. Permissions: Permissions control access to sensitive user data and system features. They protect user privacy
and prevent apps from interfering with other apps or the system. Permissions are categorized into different
protection levels based on their potential impact on user privacy and system security:
a) Normal Permissions
b) Signature Permissions
c) Dangerous Permissions
VII) Explain the process of getting API keys
Creating API keys

The API key is a unique identifier that authenticates requests associated with your project for usage and billing purposes.
You must have at least one API key associated with your project.

1. Browse the site on your browser. https://console. developers. google.com/project


2. Login with your google account.
3. Create a new project by clicking on Create Project option.
4. Add your project name and organization name in the fields present on the screen.
5. Now click on APIs and Services.
6. Enable APIs and services.
7. Select Google maps Android API
8. To create an API key for Maps click on Create credentials option and then select the API key option

Click on the API key option to generate your API key. After clicking on this option your API key will be generated

VIII) Explain concept of geo-coding and reverse geo-coding


Geocoding is the process of converting a location name or address into latitude and longitude coordinates. It helps in
finding the geographical coordinates of places and is commonly used in map-based applications. In Android, Geocoder is
a built-in class that provides geocoding functionalities using the device's internet connection or offline data.

Reverse Geocoding is the process of converting latitude and longitude into a human-readable address (e.g., street name,
city, country). In Android, Geocoder is a built-in class that provides reverse geocoding functionalities using the device's
internet connection or offline data.

For example:

IX) Describe important task to become android application


publisher.
Step 1: Create a Developer Account

Before you can publish any app on Google Play, you need to create a Developer Account. You can easily sign up for one
using your existing Google Account.

Step 2: Plan to Sell? Link Your Merchant Account

If you want to publish a paid app or plan to sell in-app purchases, you need to create a payments center profile, i.e. a
merchant account.

Step 3: Create an App

Now you have to create an application by clicking on 'Create Application'. Here you have to select your app’s default
language from the drop-down menu and then type in a title for your app.

Step 4: Prepare Store Listing


Before you can publish your app, you need to prepare its store listing. These are all the details that will show up to
customers on your app’s listing on Google Play.

Step 5: Upload APK to an App Release

Finally upload your app, by uploading APK file. Before you upload APK, you need to create an app release. You need to
select the type of release you want to upload your first app version to. You can choose between an internal test, a
closed test, an open test, and a production release.

Step 6: Provide an Appropriate Content Rating

If you don’t assign a rating to your app, it will be listed as ‘Unrated’. Apps that are ‘Unrated’ may get removed from
Google Play.

Step 7: Set Up Pricing & Distribution

Before you can fill out the details required in this step, you need to determine your app’s monetization strategy. Once
you know how your app is going to make money, you can go ahead and set up your app as free or paid.

Step 8: Rollout Release to Publish Your App

The final step involves reviewing and rolling out your release after making sure you’ve taken care of everything else.

X) WAP to send SMS

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy