You are on page 1of 20

Mobile application development

1. What is activity?with the help of neat diagram explain activity lifecycle?


In Android, an "activity" is a fundamental component of an app that represents a single screen with
a user interface. It's like a window in a desktop application. Activities are used to interact with the
user and can contain things like buttons, text fields, and other UI elements. Each screen in an
Android app is typically implemented as an activity, and the app transitions between activities as
the user interacts with it.
the Activity class provides of six methods: onCreate(), onStart(), onResume(), onPause(), onStop(),
and onDestroy()

The Android activity lifecycle refers to the series of states that an activity goes through during its lifetime
Created: The activity is created by the system.

Started: The activity is visible but may not be in the foreground. The onStart() method is called.
Resumed: The activity is in the foreground and receives user input. The onResume() method
is called. At this point, the activity is running and actively interacting with the user.
Paused: The activity loses focus but is still visible. This can happen when another activity is
launched on top. The onPause() method is called.

This state is often a good place to save data or resources that are not needed while the activity is
not in the foreground.
Stopped: The activity is no longer visible. This can happen when another activity is launched and
covers the entire screen. The onStop() method is called.

In this state, you might release resources that are not needed when the activity is not visible.
Destroyed: The activity is shut down, either because the user explicitly closed it or the system
needs to free up resources. The onDestroy() method is called.

This is the final state, and after this point, the activity is considered terminated.

2. How to explicitly set focus in android .

In Android, you can explicitly set focus to a specific view (such as an EditText, Button, or any
other focusable view) using the requestFocus() method. Here's how you can do it in code:

// Assuming you have a reference to the view you want to set focus
to View myView = findViewById(R.id.myView);

// Set focus to the view


myView.requestFocus();

3. What is android.
Android is a software package and a linux based operating system for mobile devices such as
tablet computers and smartphone. It was developed by google
. Java language is mainly used to write android code although other languages are also used. The
goal of android is to create a successful real world product that improves the mobile experience.
There are many android application in the market. The top categories are.Entertainment, tools
,communication ,productivity , music , personalization , social, gaming.
Android architechture or android software stack is categorized into 5 parts.
 Linux kernal -It is the heart of android stack and all important tasks are executed by this kernal,
It is mainly responsible for power management , how android app will consume power from
battery and how much resource it will take and how much energy it will utilize from
processor ,memory management ,an android app requires memory for working and if its does;s
get enough memory ,it will crash and fail to perform tasks so memory management is
necessary. Resource management.
Linux kernal contains device drivers that are responsible for managing memory ,resources
and power by interacting with hardware and facilitating the commincation between
hardwarea and software
 Native libraries: There are various libraries in android that are necessary for smooth working of
the app ,These libraries provide support for different mechanism in the app ,on the top of linux
kernal there are native libararies. Such as Android runtime -Dalvik Vm these are core libraries
that are responsible for running android application.
 Application framework – on the top of native libraries and android runtime there is application
framework this include android api. It provides a lot of classes and interfaces for android
application development.
 Application :On the top of android framework, there are applications. All applications such
as home, contact, settings, games, browsers are using android framework that uses android
runtime and libraries.
4. What is notification? Explain the implemention steps of
creating notification.

=> Notification is the message that appears on the screen that appears on the outside of app user
interface .
Notifications are a way for an app to alert the user about events that may require their attention,
even when the app is not currently in the foreground. Android notifications typically appear in the
notification bar at the top of the screen. They can include text, icons, and actions, providing users
with a quick way to respond to or dismiss the notification. Notifications can be used for various
purposes, such as incoming messages , updates, reminders, or alerts.
Create an explicit intent for an activity in your app

Intent intent = new Intent(this, YourActivity.class);


PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0); Build the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "channel_id")
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("Your Notification Title")
.setContentText("Your notification content.")
.setContentIntent(pendingIntent)
.setPriority(NotificationCompat.PRIORITY_DEFAULT); Show the
notification
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, builder.build());

5. Explain Radio button Designing along with


onRadioButtonClicked() method?
Ans:
In Android, a RadioButton is a UI element that allows the user to select one option from a group
of options. Typically, you use RadioGroup to group multiple RadioButton elements together so
that only one radio button within the group can be selected at a time.

Here's an example of designing a simple RadioButton group in an XML layout file:

<RadioGro
up
android:id="@+id/
radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">

<RadioButto
n
android:id="@+id/
radioButtonOption1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>

<RadioButto
n
android:id="@+id/
radioButtonOption2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2"/>

<!-- Add more RadioButton elements if needed -->

</RadioGroup>

In this example, the RadioGroup contains two RadioButton elements. The


android:orientation="vertical" attribute is used to stack the radio buttons vertically.
Now, in your corresponding activity or fragment, you can handle the radio button clicks using the
onRadioButtonClicked() method. Make sure to set the android:onClick attribute for each
RadioButton in your XML layout file to specify the method to be called when the button is
clicked. For example:

RadioButto
n
android:id ="@+id/
radioButtonOption1"
android:layout_width ="wrap_content"
android:layout_height ="wrap_content"
android:text ="Option 1"
android:onClick ="onRadioButtonClicked /
"
You need to further define the onRadioButtonClicked() method:

6. What is Async task ?with neat diagram explain steps for execution of Asynctask

Ans :AsyncTask is a class in Android that allows you to perform background operations and
publish results on the UI thread without having to manually manage threads. it is particularly
useful when you need to perform tasks in the background, such as network
operations,uploading,downloading,generating log files, recovery,updating, file I/O, or other time-
consuming operations, without freezing the user interface.
AsyncTask has three main methods that you can override to define the background task, update the
UI on the main thread, and handle any post-execution operations:

doInBackground(Params...): This method contains the code that will be executed in the
background thread. It receives input parameters, performs the background computation, and
returns the result.

onPostExecute(Result): This method is called on the UI thread after the doInBackground method
completes. It receives the result from the background operation and can update the UI with the
result.

onProgressUpdate(Progress...): This method is used to update the UI with intermediate progress


during the background computation. It is called on the UI thread, and you can use it to show
progress bars or update other UI elements.
7. how you will create store,and restore the shared preference files?

In Android, SharedPreferences is a mechanism for storing key-value pairs persistently. It's often
used to store simple app settings, user preferences, or any data that needs to persist across app
sessions. Here's how you can create, store, and restore a SharedPreferences file in Android:
Create a SharedPreferences instance:
// You typically create a SharedPreferences instance in your Activity or Application class
SharedPreferences sharedPreferences = getSharedPreferences("my_preferences",
Context.MODE_PRIVATE);
Store data in SharedPreferences:
// Get a SharedPreferences.Editor to modify the preferences SharedPreferences.Editor editor
= sharedPreferences.edit();

// Add key-value pairs to the editor


editor.putString("username", "JohnDoe");
editor.putInt("score", 100);
editor.putBoolean("isLoggedIn", true);

Restore data from SharedPreferences:


java
Copy code
// Retrieve values from SharedPreferences
String username = sharedPreferences.getString("username", ""); int
score = sharedPreferences.getInt("score", 0);
boolean isLoggedIn = sharedPreferences.getBoolean("isLoggedIn", false);

8. what is broadcast intent?explain two types of broadcast intent

In Android, a broadcast is a message that the system or apps can send to inform other components
about a particular event or state change. A Broadcast Intent is an Intent that is
broadcasted to the system or other apps to announce information or trigger actions. There are two
main types of broadcast intents:
Implicit Broadcast Intent:

Definition: An implicit broadcast intent is a broadcast that does not explicitly target a specific
component. Instead, it includes an action (a string identifier) to describe the event, and the system
decides which components should receive it based on their declared intent filters.
Explicit Broadcast Intent:
Definition: An explicit broadcast intent is a broadcast that explicitly specifies the target
component to receive the broadcast. It includes the component's class name or package name in
its intent.

9 what is intent? Explain its types

In Android, an Intent is a messaging object that is used to request an action from another app
component, such as an activity, service, broadcast receiver, or content provider. It provides a way
for different components to communicate with each other and can be used for a variety of
purposes, such as starting activities, passing data between components, and broadcasting events.
Explicit Intent: Used to start a specific component within the same app. You explicitly specify the
target component's class name. For example, if you want to start a new activity, you create an
explicit intent with the target activity's class.
Intent explicitIntent = new Intent(parameters)
Implicit intent: Used to request functionality from other components in the system.
For example, you might use an implicit intent to open the device's camera or share text.

java
Copy code
Intent implicitIntent = new Intent(parameters);
startActivity(implicitIntent);
An Intent can also carry data (extras) along with it.
10.List and explain files associated with build gradle.
: In android development build gradle plays an important role in configuring and building your
android project There are mainly two types of build gradle file associated with android.
Project level build gradle :
This file is located in the root directory of your project and is typically named, ‘Build gradle’. It
configure build setting for the entire project .
Here are the key elements.
‘Build script’ this block contains the dependencies and repositories required by the build gradle for
fininshing the project.
‘All projects’ this block is used to define the configuration setting of various elements in the
android project.
Repositoris: this block should have the repositiories where gradle should look for dependencies.
Dependencies: this block specifies the dependencies required by the gradle
Module level build gradle
This file is located with each module and is typically name build gradle .it contains build setting
specific to that module ;
It contains few elements;
Android:this block contains configuration related to android build ,sdk version, andoid version,
kernal info. Etc.
Dependencies “ this block contains the dependencies required for specific modules ..
12.what is breakpoint> how it is used in android
In Android development, a breakpoint is a marker that you can set in your code during the
debugging process. It indicates a specific line of code where the debugger should pause the
execution of the program, allowing you to inspect the program's state, variables, and step through
the code to understand its behavior.
When you set a breakpoint and run your app in debug mode, the debugger will stop the execution
at that point, allowing you to examine the values of variables, evaluate expressions, and step
through the code one line at a time. This can be incredibly helpful for identifying and fixing bugs
or understanding the flow of your program.
13.Explain fragment and its life cycle?list out methods of fragment class
In Android, the fragment is the part of Activity which represents a portion of User Interface(UI) on
the screen. Fragments were introduced to make it easier to create flexible and responsive UIs,
particularly for larger screens, such as tablets, where multiple UI components can be combined in a
single activity.
onAttach(): The fragment is attached to its hosting activity. This is the first method called in the
fragment lifecycle.

onCreate(): The fragment is created. This method is used for any setup that doesn't require the UI
to be fully created.

onCreateView(): This method is called when it's time for the fragment to draw its UI for the first
time. You should inflate the fragment's layout here and return the View.

onActivityCreated(): Called when the activity's onCreate() method has completed. This is a good
place to start interacting with the activity.

onStart(): The fragment becomes visible to the user. It's a good place to add animations or perform
other UI-related tasks.

onResume(): The fragment is interacting with the user. At this point, the fragment is active and
visible.

onPause(): The fragment is being moved to the background or is about to be detached. It's a good
place to save data or perform other cleanup.
onStop(): The fragment is no longer visible to the user. This is a good place to stop animations or
other ongoing actions.

onDestroyView(): The fragment's view is being destroyed. It's a good place to clean up resources
associated with the UI.

onDestroy(): The fragment is being destroyed. Clean up any remaining resources.

onDetach(): The fragment is being detached from its hosting activity. This is the last method in the
fragment lifecycle.
14. List and explain types of layout..
In Android app development, layouts are used to define the structure and arrangement of user
interface components within an app. Android provides several types of layout classes to help you
organize and design the user interface efficiently. Here are some common types of layouts in
LinearLayout:
LinearLayout arranges its children elements either horizontally or vertically. You
can set the orientation attribute to "horizontal" or "vertical."
It's a simple and straightforward layout, often used for creating basic UI structures. RelativeLayout:

RelativeLayout allows you to specify the position of child elements relative to each other or to the
parent.
You can use attributes like layout_alignParentTop, layout_below, etc., to define the position of
views.

FrameLayout:
FrameLayout is a simple layout that places its children on top of each other. It's
often used for displaying a single item at a time or for layering views.
ConstraintLayout:

.
TableLayout:
TableLayout organizes its children into rows and columns, like an HTML table. It is
useful when you need to display data in a tabular form.

GridLayout:
GridLayout is a grid-based layout that arranges its children in a two-dimensional grid. It's
useful for creating complex layouts where items need to be aligned in both rows and columns.
ScrollView:
ScrollView is used to provide a scrollable view when the content is too large to fit within a single
screen.
These layouts can be combined and nested to create sophisticated and responsive user interfaces in
Android apps. The choice of layout depends on the specific requirements of your UI design
15. what is service? How do you implement stated service and bound service.

In Android, a Service is a component that runs in the background to perform long-running


operations without a user interface. Services are used to perform tasks that need to continue
running even when the application is not in the foreground. There are two main types of services in
Android: Started Services and Bound Services.
Stated Service
A Started Service is initiated using startService() method, and it continues to run in the background
until it completes its task or is explicitly stopped
Intent serviceIntent = new Intent(context, MyStartedService.class); startService(serviceIntent);
Bound Service:
A Bound Service is used when components (like activities) need to interact with the service.
Implementation:
Create a Service class with a Binder:
Bind to the service from an activity:
Remember to unbind the service when it's no longer needed:
16. different android input controls with neat diagram

1 TextView
This control is used to display text
to the user.
EditText
2 EditText is a predefined subclass of TextView that includes rich editing
capabilities.
3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it
shows a list of completion suggestions automatically while the user is typing.

Button
4 A push-button that can be pressed, or clicked, by the user to perform an action.

ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact
5 location of its children. This shows a button with an image (instead of text) that
can be pressed or clicked by the user.

CheckBox
An on/off switch that can be toggled by the user. You should use check box
6 when presenting users with a group of selectable options that are not mutually
exclusive.
ToggleButton
7
An on/off button with a light indicator.

RadioButton
8 The RadioButton has two states: either checked or unchecked.

RadioGroup
9 A RadioGroup is used to group together one or more RadioButtons.

ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks,
10
such as when you are performing a task in the background

17. What is firebase real time database? How it is implemented.


Firebase Realtime Database is a cloud-hosted NoSQL database provided by Google as part
of the Firebase platform. It's designed to store and sync data in real-time between clients (such as
mobile or web applications). Here's a short and easy explanation of how to use Firebase Realtime
Database:
Key Concepts:
JSON Structure:
The data in the Firebase Realtime Database is stored as JSON (JavaScript Object Notation),
which is a lightweight data-interchange format.
Real-time Sync:
Any changes made to the data are immediately synchronized across all connected devices
in real-time. This makes it suitable for applications requiring live updates.
Steps
Create a Firebase Project:

Go to the Firebase Console, create a new project, and follow the setup instructions.
Add your App to the Project:
Register your Android or iOS app with the Firebase project. You'll get a configuration
file (google-services.json for Android, GoogleService-Info.plist for iOS).

Enable Realtime Database:


In the Firebase Console, navigate to the "Database" section and click on "Create Database."
Choose "Start in test mode" for simplicity during development.
Integrate Firebase SDK:
In your Android or iOS project, add the Firebase SDK by adding the configuration files
and the necessary dependencies.
initialize Firebase:

Write Data to the Database:

Read Data to the Database:

Security Rules:
 Define security rules in the Firebase Console to control who has read and write access
to your database.
Run your app

18. What is menu,types of menu.

In Android, a menu is a user interface component that provides a set of options or actions
that users can choose from. Menus are typically used to allow users to access various
features or functionalities within an app.
Options Menu:
The Options Menu is a common menu that appears at the top of an activity or fragment.
It typically contains actions that are relevant to the current context or screen.
Options Menu items are often represented by icons and text.
Context Menu:
The Context Menu is a floating menu that appears when the user performs a long press on a
view (such as a button, list item, or image).
Popup Menu: Khud likho iske bare me
. Toolbar Menu:
The Toolbar Menu is a menu associated with the Toolbar widget.
It is similar to the Options Menu but is more customizable and can include icons, text, and
other interactive elements.
Bottom Navigation Menu:
The Bottom Navigation Menu is a menu placed at the bottom of the screen.
It is often used for navigating between different sections or views of an app
19 .what is contextual menu? Implement floating contextual menu
contextual menu, often referred to as a "Context Menu," is a menu that provides options or
actions relevant to the context of the user's interaction. In Android, a floating contextual
menu typically appears in response to a long press on a particular view or item, offering
actions specific to that item. Here's a basic example of how to implement a floating
contextual menu in Android:
Define the Context Menu in XML:
Create a new XML resource file in the res/menu directory. For example,
res/menu/context_menu.xml:

<menu xmlns:android="http://schemas.android.com/apk/res/android"> <item


android:id="@+id/action_edit" android:title="Edit" /> <item
android:id="@+id/action_delete" android:title="Delete" /> </menu>
2. Register Views for Context Menu:

In your activity or fragment, register the views for which you want to show the contextual
menu using registerForContextMenu. This is typically done in the onCreate method:
javaCopy code
public class YourActivity extends AppCompatActivity { @Override protected void
onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); View yourView =
findViewById(R.id.your_view_id); registerForContextMenu(yourView); } // Other
methods... }
3. Create Context Menu:

Override onCreateContextMenu to inflate the context menu when a long press occurs:
javaCopy code
@Override public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v,
menuInfo); MenuInflater inflater = getMenuInflater(); inflater
Handle Context Menu Item Clicks:
@Override
public boolean onContextItemSelected(MenuItem item)
{ switch (item.getItemId()) {
case R.id.action_edit
21. what Is recycle view? Explain components of recycle view
In Android, a RecyclerView is a powerful and flexible view widget that is used to display a
scrolling list of elements, efficiently recycling and reusing viewsIt is an improvement over
the older ListView and GridView components. RecyclerView makes it easy to efficiently
display large sets of data. You supply the data and define how each item looks, and the
RecyclerView library dynamically creates the elements when they're needed.
Components:
Adapter:
This is the messenger. It carries the data and delivers it to the RecyclerView, making sure
each item knows what to show.
ViewHolder:
Imagine it as a small container, like a box, that holds the view for one item in the list. It
helps in showing items efficiently.
LayoutManager:
Think of it as the organizer. It decides how the items should be arranged in the list—
whether in a line, columns, or a grid.
ItemDecoration:
This is like adding special touches between items, such as lines or spaces, to make things
look nice and organized.
22. what is loader, explain its characteristics ,explain loader with architechture,
with neat diagram.
Loaders in Android are a set of utility classes that help in managing and loading data
asynchronously in an activity or fragment.
Here's a high-level explanation of the Loader architecture:
1. LoaderManager:
 LoaderManager is a system service that manages one or more loaders associated
with an activity or fragment.
 It's responsible for keeping track of the loaders' lifecycle and handling the data
they load.
2. Loader:
The loader is like your super-efficient assistant. It knows how to fetch data in the background
without slowing down the app

3. LoaderCallbacks:
 LoaderCallbacks is an interface that the context (activity or fragment)
implements to interact with the loader.
 It includes methods like onCreateLoader, onLoadFinished, and
onLoaderReset to handle loader creation, data loading completion, and loader
reset events.
4. data Source:
 The data source can be a content provider, a database, a network service, or any
other source of data.
 Loaders are flexible and can be adapted to various data sources.

+ + + +

| Activity/ | | LoaderManager |

| Fragment | +--------------------------+

| | | +---------------+ |

| +---------------+ | | | Loader | |

| | LoaderManager |<---------->| Callbacks | |

| | (implements || | +---------------+ |

| | LoaderCallbacks| | | +---------------+ |

| | interface) || | | Loader | |

| +---------------+ | | | | |

| | | +---------------+ |

+ + + +

| |
| + +
| |
v v
+ +
| Data Source |
| (Content Provider, |
| Database, etc.) |
+ +

23. Define permission ? how to request permission ? how to grant and revoke
permission
Permissions in Android:
Permissions in Android are security features that control an app's access to sensitive data
or certain system functionalities. They ensure that apps only access resources and
information that are necessary for their intended functionality, protecting user privacy and
security.
There are two types of permissions in Android:

1. Normal Permissions:

 These permissions are granted automatically when the app is installed.


 They don't pose a significant risk to user privacy.

2. Dangerous Permissions:

 These permissions involve accessing sensitive user data or performing potentially


harmful actions.
 Users must explicitly grant these permissions. Requesting
Permissions:

To request permissions in Android, follow these general steps:

Declare Permissions:

In your app's manifest file, declare the permissions your app needs. For dangerous
permissions, declare them as well, but remember that they will be requested at runtime.

xml
Copy code
<uses-permission android:name="android.permission.READ_CONTACTS" />
Check Permissions at Runtime:

Before using a feature that requires a dangerous permission, check if the permission is
granted.
java
Copy code
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_CONTACTS) ==
PackageManager.PERMISSION_GRANTED) {
// Permission is already granted
} else {
// Request permission ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
Handle Permission Request Result:

Override the onRequestPermissionsResult method to handle the result of the permission


request.
java
Copy code @Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults)
{

if (requestCode == MY_PERMISSIONS_REQUEST_READ_CONTACTS) {
// Check if the permission is granted
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission granted, proceed with the operation
} else {
// Permission denied, handle accordingly

}
}
}

Granting and Revoking Permissions:

Granting Permissions:

Users can grant permissions during the installation process or later in the app settings.
To grant a permission, users can go to the app settings, find the app, and manually
enable the required permission.
Revoking Permissions:

Users can also revoke permissions at any time through the app settings.
Apps need to be designed to handle scenarios where a permission is revoked, providing
a graceful degradation of functionality.
Remember to handle permissions responsibly, provide clear explanations to users about
why your app needs certain permissions, and ensure that your app gracefully handles
scenarios where permissions are denied or revoked. This is crucial for user trust and app
usability.

You might also like