0% found this document useful (0 votes)
78 views53 pages

Mobile Computing Answer

Android is an open-source, Linux-based software stack with an architecture comprising five key components: Linux kernel, native libraries, Android Runtime, Application Framework, and Applications. Developers face challenges such as fragmentation, performance optimization, UI design, security, app compatibility, memory management, and testing during Android application development. The document also explains intents in Android, their types (explicit and implicit), shared preferences advantages and disadvantages, creating menus, adaptive layouts, and SQLite database methods.
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)
78 views53 pages

Mobile Computing Answer

Android is an open-source, Linux-based software stack with an architecture comprising five key components: Linux kernel, native libraries, Android Runtime, Application Framework, and Applications. Developers face challenges such as fragmentation, performance optimization, UI design, security, app compatibility, memory management, and testing during Android application development. The document also explains intents in Android, their types (explicit and implicit), shared preferences advantages and disadvantages, creating menus, adaptive layouts, and SQLite database methods.
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/ 53

Q-1)A)What is android?

Explain android architecture


with diagram.

Android is an open-source, Linux-based software stack created


for a wide array of devices and form factors. The Android
architecture consists of several key componentsAndroid
Architecture
android architecture or Android software stack is
categorized into five parts:
1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
Let's see the android architecture first.

1) Linux kernel
It is the heart of android architecture that exists at the root of
android architecture. Linux kernel is responsible for device
drivers, power management, memory management, device
management and resource access.
2) Native Libraries
On the top of linux kernel, their are Native libraries such as
WebKit, OpenGL, FreeType, SQLite, Media, C runtime library
(libc) etc.
The WebKit library is responsible for browser support, SQLite is
for database, FreeType for font support, Media for playing and
recording audio and video formats.
3) Android Runtime
In android runtime, there are core libraries and DVM (Dalvik
Virtual Machine) which is responsible to run android application.
DVM is like JVM but it is optimized for mobile devices. It
consumes less memory and provides fast performance.
4) Android Framework
On the top of Native libraries and android runtime, there is
android framework. Android framework includes Android
API's such as UI (User Interface), telephony, resources,
locations, Content Providers (data) and package managers. It
provides a lot of classes and interfaces for android application
development.
5) Applications
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. Android runtime and native libraries are using
linuxkernal.

b) State the challenges present in the development of


android application.
Challenges Faced by Developers During Android App
Development
1. Fragmentation:
One of the biggest challenges in Android app development is
the platform's fragmentation. Unlike iOS, where there are a
limited number of devices and operating system versions to
support, Android has an extensive collection of devices with
different screen sizes, resolutions, and operating system
versions. Developing an app that works seamlessly on all
Android devices can make it challenging.
Solution:
 Conduct thorough market research to identify your target
audience's most popular devices and OS versions.
 Use responsive design techniques and ensure your app
adapts to different screen sizes and resolutions.
 Test your app on various devices and use tools like
Android Virtual Devices (AVDs) and cloud-based testing
services to cover various configurations.
 Regularly update your app to support new Android
versions and deprecate outdated features.
2. Performance Optimization:
Optimizing app performance is crucial to provide a smooth user
experience. However, Android apps often face performance
issues due to memory leaks, inefficient resource usage, and
slow network connections.
Solution:
 Implement efficient coding practices such as using
appropriate data structures, optimizing algorithms, and
minimizing memory leaks.
 Use performance profiling tools like Android Profiler and
DDMS to identify and fix performance bottlenecks.
 Optimize network requests by minimizing the number of
calls, compressing data, and implementing caching
mechanisms.
 Perform rigorous testing, including load testing, to ensure
your app performs well under different scenarios.
3. User Interface (UI) Design:
Creating an appealing and user-friendly UI is essential for the
success of any Android app. However, designing UIs that work
well across different screen sizes and resolutions can take time
and effort.
Solution:
 Follow Android's UI design guidelines (Material Design) to
ensure consistency and familiarity.
 Use responsive layout techniques like ConstraintLayout to
create adaptive UIs that adjust to various screen sizes.
 Test your app on different devices to identify and fix any
UI issues.
 Use user feedback and continuously conduct usability
testing to improve your app's UI.
4. Security:
As Android apps handle sensitive user data, ensuring robust
security measures is crucial. However, malicious attacks often
target Android, making security a significant challenge for
developers.
Solution:
 Encrypt sensitive data both during transmission and
storage.
 Implement secure authentication mechanisms like OAuth
or biometric authentication.
 Regularly update libraries and dependencies to address
security vulnerabilities.
 Use code obfuscation and other security techniques to
protect your app's source code.
 Conduct regular security audits and penetration testing to
identify and fix any vulnerabilities.
5. App Compatibility:
Ensuring app compatibility across different Android versions,
screen sizes, and hardware configurations can be complex,
leading to compatibility issues.
Solution:
 Conduct comprehensive testing on various devices, OS
versions, and configurations.
 Use Android's backward compatibility support libraries to
support older versions of the OS.
 Regularly update your app to leverage new features and
optimizations in newer Android versions.
 Use responsive design and adaptive layouts to handle
different screen sizes effectively.
6. Memory Management:
Android devices have limited memory, and inefficient memory
management can lead to app crashes and poor performance.
Solution:
 Use memory profiling tools like Android Profiler to identify
memory leaks and excessive usage.
 Avoid storing large amounts of data in memory. Use
techniques like lazy loading and pagination to load data
efficiently.
 Optimize image and resource handling by using
appropriate compression techniques and caching
mechanisms.
 Dispose of objects properly and use the garbage collector
effectively.
7. Testing and Debugging:
Thorough testing and effective debugging are essential to
ensure a high-quality Android app. However, testing on various
devices and finding and fixing bugs can be time-consuming and
challenging.
Solution:
 Implement a robust testing strategy, including unit,
integration, and UI testing.
 Utilize automated testing frameworks like Espresso or
Robolectric to streamline the testing process.
 Use crash reporting tools like Firebase Crashlytics to
identify and resolve app crashes.
 Encourage user feedback and consider implementing a
beta testing program to gather real-world insights.

Q2)A) What is intent? Explain Explicit Vs Implicit intents.


What is intent in Android?
The intent is a messaging object which passes between
components like services, content providers, activities, etc.
Normally startActivity() method is used for invoking any
activity. Some of the general functions of intent are:
1. Start service
2. Launch Activity
3. Display web page
4. Display contact list
5. Message broadcasting
Methods and their Description
Methods Description

Context.startActivity( This is to launch a new activity or get


) an existing activity to be action.
Methods Description

This is to start a new service or deliver


Context.startService()
instructions for an existing service.

Context.sendBroadca This is to deliver the message to


st() broadcast receivers.
Intent Classification:
There are two types of intents in android
1. Implicit Intent
2. Explicit Intent
Implicit Intent
Using implicit Intent, components can’t be specified. An action
to be performed is declared by implicit intent. Then android
operating system will filter out components that will respond
to the action. For Example,

In the above example, no component is specified, instead, an


action is performed i.e. a webpage is going to be opened. As
you type the name of your desired webpage and click on the
‘CLICK’ button. Your webpage is opened
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {

EditTexteditText;
Button button;

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

button = findViewById(R.id.btn);
editText = (EditText) findViewById(R.id.editText);

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String url=editText.getText().toString();
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(intent);
}
});
}
}

Explicit Intent
Using explicit intent any other component can be specified. In
other words, the targeted component is specified by explicit
intent. So only the specified target component will be
invoked. For Example:
Explicit Intent Example
In the above example, There are two activities (FirstActivity,
and SecondActivity). When you click on the ‘GO TO OTHER
ACTIVITY’ button in the first activity, then you move to the
second activity. When you click on the ‘GO TO HOME ACTIVITY’
button in the second activity, then you move to the first
activity. This is getting done through Explicit Intent.
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class MainActivity2 extends AppCompatActivity {

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

public void homeScreen(View view) {


Intent i = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(i);
}
}
b) What are the advantages and disadvantages of
shared preferences in android
Shared Preferences in Android provide a simple way to store
and retrieve small amounts of data in the form of key-value
pairs. While they are widely used for managing user
preferences and application settings, they come with both
advantages and disadvantages.
Advantages of Shared Preferences
1. Ease of Use: Shared Preferences are straightforward to
implement and require minimal setup. Developers can easily
read and write data without complex queries or additional
libraries.
2. Lightweight: They are lightweight and efficient for storing
small amounts of data, making them ideal for user preferences
or application settings.
3. Persistence: Data stored in Shared Preferences is persistent
across application sessions, meaning it will remain available
even after the app is closed or the device is rebooted.
4. Security: Shared Preferences are private to the application,
ensuring that sensitive data cannot be accessed by other
applications.
5. Simplicity: The key-value pair structure is similar to a
dictionary, making it easy to understand and manage.
Disadvantages of Shared Preferences
1. Limited Storage Capacity: Shared Preferences are not
suitable for storing large amounts of data. They are designed
for small datasets, and using them for larger data can lead to
performance issues.
2. No Query Support: Unlike databases, Shared Preferences do
not support querying capabilities, which means developers
cannot search for specific data easily.
3. Limited Data Types: They only support primitive data types
such as strings, integers, and booleans. More complex data
types require serialization or alternative storage methods.
4. Data Structure Limitations: Shared Preferences are not
designed to handle structured data, making them less suitable
for applications requiring complex data relationships.
Q. 3A)How to create menus in android? Explain with
example.
Creating menus in Android applications allows users to access
various functions and settings conveniently. Android supports
three types of menus: Options Menu, Context Menu, and Popup
Menu. Here’s how to create a simple Options Menu using XML
and Java.
Step-by-Step Guide to Creating an Options Menu
1. Create a Menu Resource File
First, create a menu resource file in the res/menu directory of
your Android project.
 Right-click on the res folder.
 Select New > Android Resource Directory.
 Choose menu as the resource type and click OK.
 Right-click on the newly created menu folder and select New >
Menu Resource File.
 Name the file (e.g., menu_example.xml).
Here’s an example of what the XML file might look like:
xml
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:icon="@drawable/ic_settings"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_about"
android:title="@string/action_about" />
</menu>
In this example, two menu items are defined: "Settings" and
"About". The android:showAsAction attribute determines how
the item is displayed in the action bar.
2. Inflate the Menu in Your Activity
Next, you need to inflate this menu in your activity. Override
the onCreateOptionsMenu method in your activity class:
java
importandroid.os.Bundle;
importandroid.view.Menu;
importandroid.view.MenuInflater;
importandroid.view.MenuItem;
importandroidx.appcompat.app.AppCompatActivity;

publicclassMainActivityextendsAppCompatActivity{
@Override
protectedvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
publicbooleanonCreateOptionsMenu(Menu menu){
MenuInflaterinflater=getMenuInflater();
inflater.inflate(R.menu.menu_example, menu);
returntrue;
}

@Override
publicbooleanonOptionsItemSelected(MenuItem item){
switch(item.getItemId()){
caseR.id.action_settings:
// Handle settings action
returntrue;
caseR.id.action_about:
// Handle about action
returntrue;
default:
returnsuper.onOptionsItemSelected(item);
}
}
}
3. Handle Menu Item Selections
In the onOptionsItemSelected method, you can handle the
actions when a menu item is selected. In the example above,
you can add the logic for what happens when the user selects
"Settings" or "About".
Summary
By following these steps, you can create a functional Options
Menu in your Android application. The menu is defined in an
XML file for better organization and separation of concerns,
making it easier to manage and modify. This approach
enhances the user experience by providing a familiar interface
for accessing app functions and settings.
Q-3)B) Write a short note on "adaptive layout "
Adaptive layouts in Android are designed to provide a seamless
user experience across a wide range of device sizes and
configurations, from smartphones to large tablets and foldable
devices. The goal of adaptive layouts is to adjust the user
interface dynamically based on the available screen space,
ensuring that the app remains usable and visually appealing
regardless of the device.
Key Features of Adaptive Layouts
1. Responsive Design: Adaptive layouts utilize responsive
design principles, allowing UI elements to resize and rearrange
themselves based on the screen dimensions. This is essential
for accommodating different orientations and screen sizes.
2. Window Size Classes: Android introduces the concept of
window size classes, which categorize devices into compact,
medium, and expanded sizes. This classification helps
developers determine how to adjust their layouts effectively
based on the available space.
3. Use of Jetpack Compose: With Jetpack Compose, developers
can create adaptive layouts more easily. The framework
provides composable functions that help manage different
layouts based on the window size classes, streamlining the
process of creating responsive UIs.
4. Alternative Layout Resources: Developers can create
alternative layouts for different screen configurations by using
resource qualifiers. This allows for specific layouts to be loaded
based on the device's characteristics, enhancing the
adaptability of the app.
5. Multi-Window Support: Adaptive layouts also consider multi-
window modes, allowing apps to adjust their UI when used
alongside other applications. This is particularly relevant for
foldable devices and larger screens, where users may run
multiple apps simultaneously.
Example of Adaptive Layout Implementation
Here's a brief example of how you might implement an
adaptive layout using Jetpack Compose:
kotlin
@Composable
funMyAdaptiveLayout(){
valwindowSizeClass=calculateWindowSizeClass()// Get the
current window size class
when(windowSizeClass.widthSizeClass){
WindowWidthSizeClass.Compact->{
// Layout for compact screens (e.g., phones)
Column {
Text("Compact Layout")
// Add other UI elements
}
}
WindowWidthSizeClass.Medium->{
// Layout for medium screens (e.g., small tablets)
Row {
Text("Medium Layout")
// Add other UI elements
}
}
WindowWidthSizeClass.Expanded->{
// Layout for expanded screens (e.g., large tablets)
Row {
Text("Expanded Layout")
// Add other UI elements
}
}
}
}
In this example, the layout adapts based on the current window
size class, allowing for different arrangements of UI elements
depending on the device's screen size.

Q4)A) What is SQLite database? Explain its method in


detail
SQLite is a self-contained, serverless, zero-configuration,
transactional SQL database engine. It is widely used for various
applications, including mobile apps, web browsers, and
embedded systems, due to its simplicity and lightweight
nature. Here’s a detailed explanation of SQLite and its
methods.
What is SQLite?
SQLite is an embedded database engine written in the C
programming language. Unlike traditional client-server
database management systems, SQLite does not require a
separate server process; instead, it operates directly on disk
files. This design allows applications to access the database
without the overhead of inter-process communication, resulting
in faster performance for simple queries.
Key Characteristics of SQLite
1. Serverless: SQLite runs in the same process as the
application, eliminating the need for a standalone database
server. This makes it easy to deploy and manage.
2. Zero Configuration: There is no setup or administration
required. Developers can simply include the SQLite library in
their applications and start using it immediately.
3. Single File Storage: A complete SQLite database is stored in
a single cross-platform disk file. This makes it easy to share,
copy, and backup databases.
4. ACID Compliance: SQLite transactions are fully ACID-
compliant, ensuring data integrity even in the event of system
crashes or power failures.
5. Lightweight: The library size is typically less than 1MB,
making it suitable for applications with limited resources, such
as mobile devices.
6. Cross-Platform: SQLite is available on various platforms,
including Windows, macOS, Linux, Android, and iOS, allowing
for easy portability of applications.
Methods of Using SQLite
To use SQLite in an application, developers typically follow
these steps:
1. Creating a Database
To create a new SQLite database, you simply need to open a
connection to a database file. If the file does not exist, SQLite
will create it automatically.
SQLiteDatabasedb=this.openOrCreateDatabase("mydatabase.
db", MODE_PRIVATE,null);
2. Creating Tables
You can define tables in the database using SQL commands.
For example:
db.execSQL("CREATE TABLE IF NOT EXISTS users (id INTEGER
PRIMARY KEY, name TEXT, age INTEGER)");
3. Inserting Data
To insert data into the database, you can use the INSERT SQL
command:
db.execSQL("INSERT INTO users (name, age) VALUES ('Alice',
30)");
4. Querying Data
To retrieve data, you can execute a SELECT statement and
process the results:

Cursorcursor=db.rawQuery("SELECT * FROM users",null);


while(cursor.moveToNext()){
int id =cursor.getInt(0);
String name =cursor.getString(1);
int age =cursor.getInt(2);
}
cursor.close();
5. Updating Data
To update existing records, use the UPDATE statement:
db.execSQL("UPDATE users SET age = 31 WHERE name =
'Alice'");
6. Deleting Data
To delete records, use the DELETE statement:

db.execSQL("DELETE FROM users WHERE name = 'Alice'");


7. Closing the Database
Finally, it is important to close the database connection when
done:
db.close();

SQLite is a powerful and versatile database engine that is ideal


for applications requiring lightweight, serverless database
solutions. Its ease of use, combined with features like ACID
compliance and cross-platform support, makes it a popular
choice for developers. By following the methods outlined
above, developers can effectively utilize SQLite to manage data
within their applications.

Q4)B) Explain content resolver and providers in android.


In Android, Content Providers and Content Resolvers are
essential components that facilitate data sharing between
applications while maintaining data security and integrity.
Content Provider
A Content Provider is a component that manages access to a
structured set of data. It acts as an intermediary between
applications and data sources, such as databases or files,
allowing applications to share data securely. Content Providers
expose data to other applications through a standardized
interface, using a content URI that adheres to
the content:// scheme.
Key Features of Content Providers:
1. Data Abstraction: Content Providers abstract the underlying
data source, allowing applications to interact with data without
needing to know the details of how it is stored.
2. CRUD Operations: They provide methods for performing
CRUD (Create, Read, Update, Delete) operations on the data.
The primary methods that must be implemented in a Content
Provider include:
 query(): Retrieves data and returns it as a Cursor object.
 insert(): Adds new data to the provider.
 update(): Modifies existing data.
 delete(): Removes data.
 getType(): Returns the MIME type of the data at a given URI.
 onCreate(): Initializes the provider when it is created.
3. Security: Content Providers enforce permissions, allowing
developers to control which applications can access their data.
This is crucial for protecting sensitive information.
Content Resolver
The Content Resolver is a class that provides a simple
interface for applications to interact with Content Providers. It
acts as a bridge between the application and the Content
Provider, handling requests for data and directing them to the
appropriate provider based on the URI provided.
Key Features of Content Resolvers:
1. Request Handling: The Content Resolver accepts requests
from clients (applications) and resolves them by directing these
requests to the correct Content Provider using its unique
authority.
2. CRUD Methods: It provides methods that correspond to the
CRUD operations defined in the Content Provider:
 insert(): To insert data.
 query(): To retrieve data.
 update(): To update data.
 delete(): To delete data.
3. URI Mapping: The Content Resolver maintains a mapping
from authorities to Content Providers, enabling it to determine
which provider to contact for a given request.
Example Workflow
When an application wants to access data from another
application's Content Provider, it follows this workflow:
1. The application creates a Content Resolver instance
using getContentResolver().
2. It constructs a URI that specifies the data it wants to access.
3. The application calls the appropriate method on the Content
Resolver (e.g., query(), insert(), etc.).
4. The Content Resolver parses the URI, determines the correct
Content Provider, and forwards the request.
5. The Content Provider processes the request and returns the
result (e.g., a Cursor with data).
6. The application receives the data and can use it as needed.
Conclusion
Content Providers and Content Resolvers are integral to the
Android architecture, enabling secure and efficient data sharing
between applications. By providing a standardized interface for
data access and enforcing security measures, they help
maintain the integrity and privacy of application data while
allowing for rich inter-application interactions. Understanding
how to implement and utilize these components is essential for
Android developers looking to create robust applications.

Q5)A)What is services? explain service life cycle.


In Android, a Service is a component that runs in the
background to perform long-running operations without
needing user interaction. Services are particularly useful for
tasks that need to continue even if the user switches to another
application or if the activity that started the service is
destroyed.
Types of Services
1. Started Service: This type of service is initiated when an
application component calls startService(). It runs in the
background indefinitely and can be stopped either by
calling stopService() or by the service itself calling stopSelf().
2. Bound Service: A bound service allows components (like
activities) to bind to it using bindService(). This creates a client-
server interface where the bound components can send
requests and receive results. The service remains active as
long as at least one component is bound to it.
Service Lifecycle
The lifecycle of a service can follow two different paths
depending on whether it is a started service or a bound service.
Each path has its own lifecycle methods that can be overridden
to manage the service's behavior.
1. Started Service Lifecycle
 onCreate(): This method is called when the service is first
created. It is where you can perform one-time initialization,
such as setting up resources.
 onStartCommand(): This method is called every time a
component starts the service using startService(). You can
implement the logic for what the service should do when it is
started. It returns an integer that indicates how the system
should handle the service if it is killed.
 onDestroy(): This method is called when the service is no
longer needed and is being destroyed. You should clean up any
resources, such as threads or listeners, in this method.
 stopSelf(): This method can be called by the service itself to
stop itself when its work is done.
2. Bound Service Lifecycle
 onCreate(): Similar to the started service, this method is
called when the service is created.
 onBind(): This method is called when a component binds to
the service using bindService(). It returns an IBinder object that
clients can use to communicate with the service.
 onUnbind(): This method is called when all clients have
disconnected from the service. You can implement cleanup
tasks here if needed.
 onRebind(): This method is called when new clients connect to
the service after it has been unbound.
Summary of Lifecycle Methods
Method Description

onCreate() Called when the service is created.

onStartComman Called when the service is started


d() with startService().

Called when a component binds to the service


onBind() with bindService().

Called when all clients have disconnected from the


onUnbind() service.

Called when new clients connect to the service


onRebind() after it was unbound.

onDestroy() Called when the service is being destroyed.


Example Implementation
Here’s a simple example of how you might implement a started
service:
java
publicclassMyServiceextendsService{

@Override
publicvoidonCreate(){
super.onCreate();
// Initialization code
}

@Override
publicintonStartCommand(Intent intent,int flags,intstartId){
// Code to perform background work
return START_STICKY;// Indicates the service should be
restarted if killed
}

@Override
publicIBinderonBind(Intent intent){
returnnull;// Not a bound service
}

@Override
publicvoidonDestroy(){
super.onDestroy();
// Cleanup code
}
}
Conclusion
Services in Android are powerful components that enable
background processing without user interaction. Understanding
the service lifecycle and how to manage it effectively is crucial
for developing responsive and efficient applications. By
leveraging started and bound services, developers can create
applications that perform tasks seamlessly in the background.

Q5 )B)Write a short note on "notification in android ".


Notifications in Android are a powerful feature that allows
applications to communicate with users even when the app is
not actively running. They provide a way to deliver timely
information, alerts, and updates to users in a non-intrusive
manner.
Key Characteristics of Notifications in Android:
1. Visibility: Notifications appear in the status bar, notification
drawer, and on the lock screen, making them easily accessible
to users.
2. Interactivity: Users can interact with notifications by tapping
on them to open the corresponding app or take specific actions
directly from the notification.
3. Customization: Developers can customize the appearance
and behavior of notifications using various properties, such as
the icon, title, text, and priority.
4. Channels: Starting from Android 8.0 (Oreo), notifications are
organized into channels, allowing users to manage and control
notifications based on their importance and category.
5. Heads-up Notifications: On Android 5.0 (Lollipop) and higher,
important notifications can appear as floating windows called
heads-up notifications, briefly interrupting the user's current
activity.
6. Notification Actions: Developers can add action buttons to
notifications, enabling users to perform specific actions without
opening the app.
7. Notification Badges: Apps can display notification badges on
their icons, indicating the presence of unread notifications.
Creating Notifications in Android
To create a notification in Android, developers typically follow
these steps:
1. Create a NotificationCompat.Builder object to set the
notification's content, such as the title, text, and icon.
2. Set the notification's priority or channel importance to
determine its intrusiveness.
3. Specify the action to be performed when the user taps the
notification by setting a content intent.
4. Build the notification using the build() method of
the NotificationCompat.Builder.
5. Publish the notification using the NotificationManager.
6. On Android 8.0 and higher, create a NotificationChannel to
group notifications and allow users to manage them based on
their importance.
Notification Lifecycle
Notifications have a lifecycle that includes creation, display,
and dismissal. They can be dismissed by the user, the system,
or the app itself. When a notification is dismissed, it is removed
from the status bar and notification drawer.
Conclusion
Notifications are an essential part of the Android user
experience, allowing apps to keep users informed and engaged
even when the app is not actively in use. By leveraging the
power of notifications, developers can create more interactive
and responsive applications that provide a better overall user
experience.

Q6)A)Explain Google Cloud messages in android.


Google Cloud Messaging (GCM) was a service that allowed
developers to send data from their server to user devices with
Android apps. It enabled push notifications and messaging to
keep users engaged. GCM has been superseded by Firebase
Cloud Messaging (FCM).Here are the key points about GCM and
how it works:
GCM Architecture
 GCM used server APIs and SDKs maintained by Google to send
push notifications and application data to Android apps.
 When an app registered with GCM, it received a unique
registration ID from Google's servers.
 The app would send this registration ID to the developer's
server to be stored.
 To send a message, the developer's server would send an API
request to GCM with the registration ID, message data, and
other parameters.
 GCM would then deliver the message to the Android device
associated with that registration ID.
GCM Features
 Supported sending push notifications with up to 4KB of payload
data.
 Provided reliable message delivery, queuing messages when
devices were offline.
 Allowed sending messages to specific devices or topics.
 Was free to use for developers.
Transition to Firebase Cloud Messaging
In 2016, Google announced Firebase Cloud Messaging (FCM)
which combined GCM and Firebase into a unified platform for
messaging and analytics.The key differences are:
 FCM is integrated with the Firebase platform, while GCM was a
standalone service.
 FCM supports sending messages to iOS and web apps in
addition to Android.
 FCM provides additional features like analytics, A/B testing, and
in-app messaging.
To use push notifications in Android today, developers should
integrate Firebase Cloud Messaging into their apps. The overall
architecture and concepts are similar to GCM, but with a more
comprehensive set of tools and features provided by the
Firebase platform

Q6)B)What are the different built in sensors are there in


android powered devices
Generally, most of the android devices have built-in sensors to
measure motion, orientation, and various environmental
conditions. These sensors will provide raw data with high
accuracy and are useful to monitor three-dimensional device
movement or positioning or monitor changes in the ambient
environment near a device.

For example, to report changes in the environment a weather


application might use a temperature sensor and humidity
sensor or a travel application might use the geomagnetic field
sensor and accelerometer to report a compass bearing, etc.

The android mainly supports three categories of sensors those


are,

Category Description

Motion These sensors are useful to measure acceleration


Sensors forces and rotational forces along three axes. This
category includes accelerometers, gravity sensors,
gyroscopes, and rotational vector sensors.

Environmenta These sensors are useful to measure various


l Sensors environmental parameters, such as ambient air
Category Description

temperature and pressure, illumination, and


humidity. This category includes barometers,
photometers, and thermometers.

Position These sensors are useful to measure the physical


Sensors position of a device. This category includes
orientation sensors and magnetometers.
Android provided a framework called sensor framework to
access all the sensors available on device and to get all the raw
sensor data. The sensor framework provided a wide variety of
sensor-related tasks. For example, by using a sensor
framework we can perform the following things

 It lists all the available sensors on the device


 It determines the capabilities of each sensor, such as its
maximum range, manufacturer, power requirements, and
resolution.
 It can acquire raw sensor data and define the minimum
rate at which you acquire sensor data.
 Register and unregister sensor event listeners that
monitor sensor changes.
The Android sensor framework will allow us to access many
types of sensors, some of these sensors are hardware-based
and some are software-based. The Hardware-based sensors are
physical components built on the handset or tablet device and
Software-based sensors are not physical devices but they
mimic Hardware-based sensors.

The Android sensor framework provided the following classes


and interfaces to access device sensors and acquire raw sensor
data.

Class Description

SensorManager By using this class we can create an


instance of sensor service and this class
provides a various methods for accessing
and listing sensors, registering and
unregistering sensor event listeners and
Class Description

acquiring orientation information.

Sensor By using this class we can create an


instance of a specific sensor and this class
provides various methods that let you
determine the sensor's capabilities.

SensorEvent The system uses this class to create a


sensor event object and it provides the raw
sensor data, type of sensor that generated
the event, accuracy of the data, and the
timestamp for the event.

SensorEventListe We can use this interface to create two


ner callback methods that receive notifications
(sensor events) when sensor values change
or when sensor accuracy changes.
.

public
class MainActivity extends AppCompatActivity implements Sens
orEventListener {
private SensorManager mgr;
private Sensor sensor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mgr =
(SensorManager)getSystemService(Context.SENSOR_SERVICE);
sensor = mgr.getDefaultSensor(Sensor.TYPE_LIGHT);
List<Sensor>deviceSensors
= mgr.getSensorList(Sensor.TYPE_ALL);
}
@Override
public final void onAccuracyChanged(Sensor
sensor, int accuracy) {
// Do something here if sensor accuracy changes.
}
@Override
public final void onSensorChanged(SensorEvent event) {
// Do something with this sensor value.
}
@Override
protected void onResume() {
super.onResume();
mgr.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}

Describe the different features of Android.

User Interface: The user interface of the Android operating


system is straight forward, and these features make it very
user friendly.
Multiple Language Support: Android supports multiple
languages in its operating system and one can change the
language very easily based on one’s requirement, the
International languages supported are English, Germany,
Chinese, Dutch, French, German, Japanese, Korean, Russian,
and many more also some native language of India is also
Supported Like Hindi, Marathi, Gujarati, Punjabi and many
more.
Multi-tasking: Android provides support to run apps and
services in the background with ease which allows the users to
use multiple apps at the same time.
Connectivity: Android has extensive support to the
connectivity and it supports connectivity such as WiFi,
Bluetooth, Hotspot, CDMA, GSM, NFC, VOLTE, UBB, VPN, 3G
network band, and 4G Network Band.
Extensive Application Support: Android have Play store
which is used as the major tool to download and update
applications on the operating system, however, one can
download the installer(often called as APK file) and install it
manually, but it is not much recommended as third party
applications could be prone to some security breach in the
smartphones.

List and elaborate steps to deploy an Android


application on Google play store.
Steps to deploy and Android Application on Google Play Store:
Step 1: Make a Developer Account
Step 2: Plan to Sell? Link Your Merchant Account
Step 3: Create an App
Step 4: Prepare Store Listing
Step 5: Upload APK to an App Release
Step 6: Provide an Appropriate Content Rating
Step 7: Set Up Pricing & Distribution
Step 8: Rollout Release to Publish Your App

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. You’ll need to pay a one-time registration fee
of $25 using your international credit or debit card. It can take
up to 48 hours for your registration to be fully processed.
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. A
merchant account will let you manage your app sales and
monthly payouts, as well as analyze your sales reports right in
your Play Console.
Step 3: Create an App Now you have 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. The title of your app will show on
Google Play after you’ve published.
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. You not necessarily complete it at once , you can always
save a draft and revisit it later when you’re ready to publish.
The information required for your store listing is divided into
several categories such as Product Details containing title,
short and full description of the app, Your app’s title and
description should be written with a great user experience in
mind. Use the right keywords, but don’t overdo it. Make sure
your app doesn’t come across as spam-y or promotional, or it
will risk getting suspended on the Play Store.
Graphic Assets where you can add screenshots, images,
videos, promotional graphics, and icons that showcase your
app’s features and functionality.
Languages & Translations, Categorization where in
category can be selected to which your app belong to. Contact
Details , Privacy Policy for apps that request access to
sensitive user data or permissions, you need to enter a
comprehensive privacy policy that effectively discloses how
your app collects, uses, and shares that data.
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. group of users before you make it
go live for everyone to access.
This is a safer option because you can analyze the test results
and optimize or fix your app accordingly if you need to before
rolling it out to all users. Once you create a production
release, your uploaded app version will become accessible to
everyone in the countries you choose to distribute it in and
click on ‘Create 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.
To rate your app, you need to fill out a content rating
questionnaire An appropriate content rating will also help you
get to the right audience, which will eventually improve your
engagement rates.
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. You can always change your app
from paid to free later, but you cannot change a free app to
paid. For that, you’ll need to create a new app and set its
price.
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. Before you
review and rollout your release, make sure the store listing,
content rating, and pricing and distribution sections of your
app each have a green check mark next to them. Once you’re
sure about the correctness of the details, select your app and
navigate to ‘Release management’ – ‘App releases.’ You can
always opt for reviews by clicking on ‘Review’ to be taken to
the ‘Review and rollout release’ screen. Here, you can see if
there are any issues or warnings you might have missed out
on. Finally, select ‘Confirm rollout.’ This will also publish your
app to all users in your target countries on Google Play

Describe with example, how to create a simple


database in SQLite (Assume suitable data)
This procedure is by openOrCreateDatabase()
1. The package imported into the application is
android.database.sqlite.SQLiteDatabase.
2. Here the class used is SQLiteDatabase.
3. The method used to create the database or connect to the
database is openOrCreateDatabse() method.
Program: activity_main.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_par
ent"
android:layout_height="match_p
arent"
tools:context=".MainActivity">
<Button
android:text="Create SQLite
Database"
android:layout_width="fill_pare
nt"
android:layout_height="wrap_c
ontent"
android:layout_centerHorizontal
="true"
android:layout_marginTop="46
dp" android:id="@+id/button"
/>
</RelativeLayout>

MainActivity.java

package
in.edu.vpt.insertusingasyn
c; import
android.app.ProgressDialo
g; import
android.content.Context;
import
android.database.sqlite.SQLiteDat
abase; import android.os.Bundle;
import
android.support.v7.app.AppCompatA
ctivity; import android.view.View;
import android.widget.Button;;

public class MainActivity extends


AppCompatActivity { SQLiteDatabase
sqLiteDatabaseObj;
Button EnterData;

@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState
);
setContentView(R.layout.activity_m
ain);
createData =
(Button)findViewById(R.id.button);
createData.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
sqLiteDatabaseObj =
openOrCreateDatabase("AndroidJSonDataBase",
Context.MODE_PRIVATE, null);
} });
}

Write down the steps to install and configure Android


studio.
Step 1: Go to
https://developer.android.com/android-studio/download to get
the Android Studio executable or zip file.
Step 2:
● Click on the Download Android Studio Button.
● Click on the “I have read and agree with the above terms
and conditions” checkbox followed by the download
button
● Click on the Save file button in the appeared prompt box
and the file will start downloading.
Step 3: After the downloading has finished, open the file
from downloads and will prompt the following dialog box.
Click on next. In the next prompt, it’ll ask for a path for
installation. Choose a path and hit next.
Step 4: It will start the installation, and once it is completed, it
will be like the image shown below.
Step 5: Once “Finish” is clicked, it will ask whether the
previous settings need to be imported [if the android studio
had been installed earlier], or not. It is better to choose the
‘Don’t import Settings option’. Click the OK button.
Step 6: This will start the Android Studio. Meanwhile, it will be
finding the available SDK components.
Step 7: After it has found the SDK components, it will redirect
to the Welcome dialog box.
Choose Standard and click on Next. Now choose the theme,
whether the Light theme or the Dark one. The light one is
called the IntelliJ theme whereas the dark theme is called
Darcula. Choose as required. Click on the Next button.
Step 8: Now it is time to download the SDK components. Click
on Finish. Components begin to download let it complete. The
Android Studio has been successfully configured. Now it’s
time to launch and build apps. Click on the Finish button to
launch it.
Step 9: Click on Start a new Android Studio project to
build a new app.
Describe Android service life cycle along with diagram.
● A service is an application component which runs
without direst interaction with the user in the
background.
● Services are used for repetitive and potentially long
running operations, i.e., Internet downloads, checking for
new data, data processing, updating content providers
and the like.
● Service can either be started or bound we just need to
call either startService() or bindService() from any of
our android components. Based on how our service
was started it will either be “started” or “bound”
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 it 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 InterProcess 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 wont be
invoked. Ideally one time setup and intializing 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
indefinetly.
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.
State and elaborate the syntax of required class and
methods for Geocoding.

Geocoder:
A class for handling geocoding and reverse geocoding.
Geocoding is the process of transforming a street address
or other description of a location into a (latitude, longitude)
coordinate.
Reverse geocoding is the process of transforming a (latitude,
longitude) coordinate into a (partial) address. The amount of
detail in a reverse geocoded location description may vary,
for example one might contain the full street address of the
closest building, while another might contain only a city name
and postal code.
The Geocoder class requires a backend service that is not
included in the core android framework.
The Geocoder query methods will return an empty list if there
no backend service in the platform. Use the isPresent()
method to determine whether a Geocoder implementation
exists.
Syntax
Geocoder (Context context)

Constructs a Geocoder localized for

the default locale. Geocoder(Context

context, Locale locale)

Constructs a Geocoder localized for the given locale.

Methods with Syntax


a. getFromLocation

Syntax

public List<Address> getFromLocation (double latitude,


double longitude, int maxResults)
public void getFromLocation (double latitude, double
longitude, int maxResults, Geocoder.GeocodeListener
listener)

This method returns an array of Addresses that attempt to


describe the area immediately surrounding the given latitude
and longitude. The returned addresses should be localized for
the locale provided to this class's constructor.
b. getFromLocatio
nName Syntax :

● public List<Address> getFromLocationName (String


locationName, int maxResults, double
lowerLeftLatitude, double lowerLeftLongitude,
double upperRightLatitude, double
upperRightLongitude)
● public void getFromLocationName (String
locationName, int maxResults, double
lowerLeftLatitude, double lowerLeftLongitude, double
upperRightLatitude, double upperRightLongitude,
Geocoder.GeocodeListener listener)
● public void getFromLocationName (String
locationName, int maxResults,
Geocoder.GeocodeListener listener)
● public List<Address> getFromLocationName
(String locationName, int maxResults)

Returns an array of Addresses that attempt to describe the


named location, which may be a place name such as "Dalvik,
Iceland", an address such as "1600 Amphitheatre Parkway,
Mountain View, CA", an airport code such as "SFO", and so
forth. The returned addresses should be localized for the
locale provided to this class's constructor.
c. isPresent
syntax
public static boolean isPresent ()
Returns true if there is a geocoder implementation present
that may return results. If true, there is still no guarantee
that any individual geocoding attempt will succeed.
Explain with example, code to create GUI using
absolute layout (Assume suitable data)
● AbsoluteLayout is based on the simple idea of placing each
control at an absolute position. We specify the exact x
and y coordinates on the screen for each control. This is
not recommended for most UI development (in fact
AbsoluteLayout is currently deprecated) since absolutely
positioning every element on the screen makes an
inflexible UI that is much more difficult to maintain.

Absolute Layout
● An Absolute Layout lets you specify exact locations (x/y
coordinates) of its children. Absolute layouts are less
flexible and harder to maintain than other types of layouts
without absolute positioning. AbsoluteLayout is based on
the simple idea of placing each control at an absolute
position.
● We specify for the exact x and y corodinates on the screen
for every control. So this recommended for most UI
development (in fact Absolute Layout is currentaly
deprecated)since absolute positioning of every element on
the screen makes an inflexible UI that is much more
difficult to maintain.
● Consider what happens if a control needs to be added to
the user interface UI, we would have to change the position
of every single element that is shifted by the new control.
This allows child views to be positioned at specified X and Y
coordinates within the containing layout view.
● <AbsoluteLayoutxmlns:android="http://
schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
● android:layout_height="fill_parent">
● <TextView
android:layout_x="110px"
android:layout_y="110px"
android:text="User Name"
android:layout_width="wrap_c
ontent"
● android:layout_height="wrap_content" />
● <EditText
android:layout_x="250p
x"
android:layout_y="80px
" android:width="100px"
android:layout_width="200
dp"
● android:layout_height="wrap_content" />
● <TextView
android:layout_x="110px"
android:layout_y="200px"
android:text="Password"
android:layout_width="wrap_c
ontent"
● android:layout_height="wrap_content" />
● <EditText
android:layout_x="250p
x"
android:layout_y="150p
x" android:width="100px"
android:layout_width="200
dp"
● android:layout_height="wrap_content" />
● <Button
android:layout_width="wrap_con
tent"
android:layout_height="wrap_co
ntent" android:text="Log In"
android:layout_x="300px"
android:layout_y="300px"/>
● </AbsoluteLayout>

Write a program to demonstrate Date and Time picker


activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="mat
ch_parent"
tools:context=".MainActivit
y">

<TextView
android:id="@+id/tvDa
te"
android:layout_width=
"149dp"
android:layout_height
="46dp"
android:layout_marginEn
d="224dp"
android:layout_marginBotto
m="312dp"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<Button
android:id="@+id/b
tnDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="96dp"
android:layout_marginBottom="312dp"
android:text="Set Date"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="DuplicateClickableBoundsCheck" />
<DatePicker
android:id="@+id/dtpcke
r"
android:layout_width="3
14dp"
android:layout_height="
293dp"
android:layout_marginBotto
m="368dp"
android:datePickerMode="s
pinner"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.36"
app:layout_constraintStart_toStartOf="parent" />

<TimePicker
android:id="@+id/timepc
ker"
android:layout_width="1
84dp"
android:layout_height="
195dp"
android:layout_marginEnd=
"132dp"
android:layout_marginBotto
m="108dp"
android:timePickerMode="s
pinner"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />

<TextView
android:id="@+id/tvTime"
android:layout_width="130dp"
android:layout_height="
56dp"
android:layout_marginEnd
="232dp"
android:layout_marginBott
om="40dp"
android:textSize="20dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/b
tnTime"
android:layout_width="wrap_co
ntent"
android:layout_height="wrap_co
ntent"
android:layout_marginEnd="104dp"
android:layout_marginBottom="48d
p" android:text="Set Time"
app:layout_constraintBottom_toBott
omOf="parent"
app:layout_constraintEnd_toEndOf=
"parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.datepickereg;
import
androidx.appcompat.app.AppCompatA
ctivity; import
android.app.DatePickerDialog;
import
android.app.TimePickerDial
og; import
android.os.Bundle;
import
android.view.View;
import
android.widget.Button
;
import
android.widget.DatePicke
r; import
android.widget.TextView;
import
android.widget.TimePicke
r; import
java.util.Calendar;

public class MainActivity extends AppCompatActivity {


TextView
tvDate,tvTime;
DatePicker
dtpcker;
TimePicker
timepcker; Button
b1,b2;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvDate=findViewById(R.id.tvDate);
tvTime=findViewById(R.id.tvTime);
b1=findViewById(R.id.btnDate);
b2=findViewById(R.id.btnTime);
dtpcker=findViewById(R.id.dtpcker
);
timepcker=findViewById(R.id.time
pcker); b1.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View view) {
tvDate.setText("Date: "+dtpcker.getDayOf
Month()+"-
"+dtpcker.getMonth()+"-"+dtpcker.getYear());
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
tvTime.setText(timepcker.getCurrentHour()
+":"+timepcker.getCurrentMinute());
}
});
}
}

Describe multimedia framework of Android with


diagram.
● The android multimedia system includes multimedia
applications, multimedia frameworks, OpenCore engine
and hardware abstract for audio/video input/output
devices. And the goal of the android multimedia
framework is to provide a reliable interface for java
services. The multimedia framework consists of several
core dynamic libraries such as libmediajni, libmedia,
libmediaplayservice and so on.
● Java classes call the Native C library Libmedia through
Java JNI(Java Native Interface). Libmedia library
communications with Media Server guard process
through Android’s Binder IPc (inter process
communication) mechanism.
● Media Server process creates the corresponding
multimedia service according to the Java multimedia
applications.
The whole communication between Libmedia and Media
Server forms a Client/Server model

Android Multimedia Framework Architecture


● Typical video/audio data stream works in Android as
follows. Particularly, Java applications first set the URI of
the media (from file or network) to PVPlayer through Java
framework, JNI and Native C. In this process, there are no
data stream flows.
● Then PVPlayer processes the media data stream with the
steps: demux the media data to separate video/audio
data stream, decode video/audio data, sync
video.audio time, send the decoded data out.
● The below is the description of media codec/format,
container and network protocol supported by the Android
platform.
1. Container: The audio file format is a file for
storing digital audio data on a system. This data
can be manipulated to reduce the size or change
the quality of the audio. It is a kind of container to
store audio information.
2. Audio Format: Any format or codec can be used
including the ones provided by Android or those
which are specific devices. However it is
recommended to use the specified file formats as
per devices.
Network Protocol: Protocols such as RTSP, HTTP,HTTPS
are supported in audio and video playback

Discuss developer console with at least four


features

● 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 devs 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

Write a program to demonstrate declaring and


using permissions with any relevant example
Permission declaring :
The permissions are declared in AndroidManifest.xml file
under Manifest folder. Permission can be set by <uses-
permission> tag in AndroidManifest.xml.
Example:
example is to send SMS
AndroidManifest.xml
<uses-permission
android:name="android.permission.SEND_SMS"/>

activity_main.xml
<?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:layout_width="match_parent"
android:layout_height="match_parent
" tools:context=".MainActivity">

<TextView
android:id="@+id/textVie
w"
android:layout_width="81
dp"
android:layout_height="4
1dp"
android:layout_marginEn
d="268dp"
android:layout_marginBottom="576
dp" android:text="To :"
app:layout_constraintBottom_toBott
omOf="parent"
app:layout_constraintEnd_toEndOf=
"parent"/>

<TextView
android:id="@+id/textVie
w2"
android:layout_width="70
dp"
android:layout_height="4
3dp"
android:layout_marginEn
d="276dp"
android:layout_marginBottom="512
dp" android:text="Sms Text"
app:layout_constraintBottom_toBott
omOf="parent"
app:layout_constraintEnd_toEndOf=
"parent" />

<EditText
android:id="@+id/
etPhno"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:layout_marginEnd="40dp"
android:layout_marginBottom="572
dp" android:ems="10"
android:inputType="textPersonNam
e"
app:layout_constraintBottom_toBott
omOf="parent"
app:layout_constraintEnd_toEndOf=
"parent" />

<EditText
android:id="@+id/etm
sg"
android:layout_width=
"193dp"
android:layout_height
="51dp"
android:layout_marginEnd="56dp"
android:layout_marginBottom="504dp"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
tools:ignore="SpeakableTextPresentCheck" />
<Button
android:id="@+id/btnSms"
android:layout_width="wrap_conten
t"
android:layout_height="wrap_conte
nt"
android:layout_marginEnd="156dp"
android:layout_marginBottom="400
dp" android:text="SEND SMS"
app:layout_constraintBottom_toBott
omOf="parent"
app:layout_constraintEnd_toEndOf=
"parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java
package com.example.testreceivesms;
import
androidx.appcompat.app.AppCompatA
ctivity; import
androidx.core.app.ActivityCompat;
import
androidx.core.content.ContextCo
mpat; import android.Manifest;
import android.content.IntentFilter;
import
android.content.pm.PackageMan
ager; import android.os.Bundle;
import
android.telephony.SmsMana
ger; import
android.view.View;
import
android.widget.Button;
import
android.widget.EditText
; import
android.widget.Toast;

public class MainActivity extends


AppCompatActivity { EditText et1,et2;
Button
b1;
@Overri
de
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState
);
setContentView(R.layout.activity_m
ain);
et1=findViewById(R.id.etPhno);
et2=findViewById(R.id.etmsg);
b1=findViewById(R.id.btnSms);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.SEN D_SMS)!=
PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.t
his,new String[]
{Manifest.permission.SEND_SMS},100);
}
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void
onClick(View v) {
try {
String phno=
et1.getText().toString();
String
msg=et2.getText().toStri
ng();
SmsManager smsManager=
SmsManager.getDefault();
smsManager.sendTextMessage(phno,
null,msg,null,null);
Toast.makeText(MainActivity.this,"Sms
sent successfully",
Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(MainActivity.this,"Sms
failed to send... try again",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Develop an application to display Google map with
user's current location.
act ivity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<fragment
android:layout_width="match
_parent"
android:layout_height="matc
h_parent"
android:id="@+id/google_ma
p"
android:name="com.google.android.gms.maps.SupportMap
Fragment" />
</RelativeLayout>
MainActivity.Java
package
com.example.location;
import
androidx.annotation.NonN
ull;
import
androidx.appcompat.app.AppCompatA
ctivity; import
androidx.core.app.ActivityCompat;
import
androidx.fragment.app.FragmentA
ctivity; import android.Manifest;
import
android.content.pm.PackageMan
ager; import
android.location.Location;
import
android.os.Bundle;
import
android.widget.Toast;
import
com.google.android.gms.location.FusedLocationPr
oviderClient; import
com.google.android.gms.location.LocationServices
;
import
com.google.android.gms.maps.CameraUpd
ateFactory; import
com.google.android.gms.maps.GoogleMap;
import
com.google.android.gms.maps.OnMapRead
yCallback; import
com.google.android.gms.maps.SupportMap
Fragment; import
com.google.android.gms.maps.model.LatLn
g;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
public class MainActivity extends FragmentActivity implements
OnMapReadyCallback
{
Location currentlocation;
FusedLocationProviderClient
fusedLocationProviderClient; private
static final int REQUEST_CODE = 101;

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

fusedLocationProviderClient =
LocationServices.getFusedLocationProviderClient(this);
fetchLastLocation();
}

private void fetchLastLocation() {

if
(ActivityCompat.checkSelfPermission(t
his,
Manifest.permission.ACCESS_FINE_LOC
ATION) !=
PackageManager.PERMISSION_GRANTE
D &&
ActivityCompat.checkSelfPermission(th
is,
Manifest.permission.ACCESS_COARSE_L
OCATION) !=
PackageManager.PERMISSION_GRANTE
D) {
ActivityCompat.requestPermissions(this,new
String[]
{Manifest.permission.ACCESS_FINE_LOCATION},REQUE
ST_CODE);
return;
}
Task<Location> task =
fusedLocationProviderClient.getLastLocation();
task.addOnSuccessListener(new
OnSuccessListener<Location>() { @Override
public void onSuccess(Location location) {
if(location!=null)
{
currentlocation=location;

Toast.makeText(getApplicationContext(),currentlocation
.getLatitude()+""+current location.getLongitude(),
Toast.LENGTH_SHORT).show();
SupportMapFragment supportMapFragment =
(SupportMapFragment)getSupportFragmentManager().
findFragmentById(R.id.go ogle_map);
supportMapFragment.getMapAsync(MainActivit
y.this);
}
}
});
}
@Override
public void onMapReady(@NonNull
GoogleMap googleMap) { LatLng
latLng=new
LatLng(currentlocation.getLatitude(),currentlocation.
getLongitude()); MarkerOptions
markerOptions=new
MarkerOptions().position(latLng)
.title("I am Here");
googleMap.animateCamera(CameraUpdateFactory.newLa
tLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.newLa
tLngZoom(latLng,5));
googleMap.addMarker(markerOptions);

}
@Override
public void onRequestPermissionsResult(int
requestCode, @NonNull String[] permissions, @NonNull
int[] grantResults) {
super.onRequestPermissionsResult(requestCode,
permissions, grantResults); switch (requestCode) {
case REQUEST_CODE:
if (grantResults.length > 0 &&
grantResults[0] ==
PackageManager.PERMISSION_GRANTED)
{ fetchLastLocation();
}
break;
}
}
}

You might also like