0% found this document useful (0 votes)
25 views17 pages

Mobile App Dev Report

Uploaded by

malviyaastha855
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)
25 views17 pages

Mobile App Dev Report

Uploaded by

malviyaastha855
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/ 17

A Report On

Networking in Android Services


Submitted in partial fulfillment of the
requirements for the award of the degree
of
Bachelor of Technology-CSE
Submitted by
Astha Malviya
202110101110093
Submitted to
Mr.Prashant Singh
(Assistant Prof.)

FACULTY OF COMPUTER SCIENCE AND ENGINEERING SHRI RAMSWAROOP


MEMORIAL UNIVERSITY, LUCKNOW-DEVA ROAD, U.P., INDIA
October, 2024
Report on Networking in Android Services

1. Overview Of Android Services


1.1 Definition and Importance of Android Services-
Android services are application components that enable long-running operations to
continue independently of a user interface. Unlike activities, which are designed to handle
direct user interactions, services function in the background, performing tasks that need to
persist beyond the lifespan of a single activity. Services are ideal for handling processes
that do not require user input, such as downloading files, playing music, or
communicating with remote servers. By allowing applications to offload time-consuming
or network-heavy tasks from the main thread, Android services help maintain a smooth
user experience and prevent application lag or freezing.

1.2 Why Services Are Essential for Background Tasks ?


Android’s emphasis on responsive user interfaces means that applications are encouraged
to avoid performing intensive tasks on the main thread. Services play an essential role
here by enabling background execution of operations. For instance, a service could run in
the background to fetch updates from a server, sync data, or upload files without
interrupting user activity or waiting for a user-triggered action. This background
processing is particularly beneficial for maintaining real-time data in applications or
enabling features like offline storage synchronization, which depend on periodically
updated data.

1.3 Distinction Between Services and Other Android Components


Android applications are typically made up of several components, each with a distinct role:
1. Activities: Activities represent the user-facing part of an application. They are
responsible for managing user interactions and UI elements. When an activity goes
out of focus (e.g., the user navigates away or the app goes to the background), it may
be stopped or destroyed, making it unsuitable for long-running tasks.
2. Broadcast Receivers: Broadcast receivers allow apps to listen for and respond to
system-wide or application-specific broadcasts (e.g., changes in network
connectivity). They are passive receivers and typically perform lightweight tasks in
response to a specific event, making them less ideal for long-term background
processing.

3. Services: Services, unlike activities and broadcast receivers, are designed to perform
persistent or periodic tasks in the background. user navigates away from the app.

1.4 Types of Android Services and Their Roles in Network


Communication-
Android offers two primary types of services, each suited to different use cases for
network-related tasks:
1. Started Services: Started services are initiated by an application component (e.g., an
activity), perform a single operation, and typically stop once the task is complete. For
example, a started service might be used to download a file from the internet. Started
services are suited for one-off tasks that don’t require continuous interaction.
IntentService is a commonly used class for started services, as it automatically stops
itself once the task is done.
2. Bound Services: Bound services provide a client-server interface, allowing other
components (e.g., activities or fragments) to bind to the service and communicate
with it. This is especially useful for real-time communication tasks, like streaming
music or handling chat interactions, where the app needs an ongoing connection with
the service. A bound service allows multiple clients to interact with it simultaneously,
making it ideal for handling shared data or services within an application.
Both types of services play essential roles in enabling network communication within
Android applications. For example, a started service can handle a one-time download
request, while a bound service can maintain an open connection for continuous data
updates. Together, these services allow Android applications to efficiently manage
background operations and network requests, enhancing app performance and
responsiveness.
2.Android Service Lifecycle

2.1 Android Service Lifecycle Breakdown –


Android services operate with their own distinct lifecycle to support background tasks
without requiring user interaction. Unlike activities, services can persist and execute
processes even when the user is not actively interacting with the application.
Understanding the lifecycle methods is essential for managing resources effectively,
preventing memory leaks, and ensuring stable, efficient background execution. The
service lifecycle includes specific methods that mark the start, operation, and termination
of a service.
The main lifecycle methods for Android services include onCreate(), onStartCommand(),
onBind(), and onDestroy(). These methods help manage the initialization, execution, and
shutdown of services.
1. onCreate(): This method is called when the service is first created. It initializes any
resources the service may need and prepares it for operation.
Purpose: Setup resources such as network connections, data structures, or
background threads that will be used by the service.
Best Practices: Since onCreate() is called only once in the lifecycle of a
service, use it to perform essential initializations. Avoid long-running or
intensive operations here to prevent delays in service startup.
2. onStartCommand(): This method is called every time a component, such as an
activity, explicitly starts the service using startService(). The method contains the core
functionality of a started service.
Purpose: Handle service requests, perform the primary task, and determine
whether the service should be restarted if terminated.
Return Values: onStartCommand() can return various constants, such as:
 START_STICKY: Restarts the service automatically if it’s terminated
by the system.
 START_NOT_STICKY: Does not restart the service if it’s terminated,
typically used for one-off operations.
 START_REDELIVER_INTENT: Restarts the service and re-delivers
the last intent, often used for time-consuming tasks that need to
complete.
Best Practices: Avoid running complex tasks directly on the main thread; use
separate threads to handle intensive work. Additionally, ensure to stop the
service manually if it’s not set to restart, preventing resource waste.
3. onBind(): This method is called when another component binds to a service using
bindService(). It’s only used by bound services, which support client-server
communication within an app.
Purpose: Return an IBinder interface for interacting with the service.
Best Practices: Since multiple clients may bind to a service, carefully manage
shared resources. Avoid holding references to activities or contexts, as this can
lead to memory leaks.
4. onDestroy(): This method is called when the service is no longer needed or the
system decides to stop it to free up resources. It is the final method in a service’s
lifecycle and ensures cleanup.
Purpose: Release any resources held by the service, stop threads, and
disconnect from remote services.
Best Practices: Always use onDestroy() to release resources, avoid leaks, and
gracefully terminate any background processes. Failing to free up resources
can lead to memory leaks and impact device performance.

Lifecycle Diagrams-

2.2 Android Service Lifecycle Management for Stability-


Efficient lifecycle management is critical to avoid resource waste, improve
performance, and ensure a responsive user experience, especially for network-based
tasks. Below are best practices for handling service lifecycle methods:
1. Memory Management:
-Avoid holding strong references to activities, contexts, or views within services, as
these can lead to memory leaks.
-For network tasks, use lightweight resources and consider caching mechanisms to
reduce repeated operations and data downloads.
2. Threading and Concurrency:
-Use threads, handlers, or AsyncTask (or Coroutine for Kotlin) to handle time-
consuming tasks in onStartCommand() or onBind(). Never execute network
operations on the main thread to avoid application freezes.
-IntentService is useful for started services as it automatically handles background
threading and stops itself once the task is done.
3. Graceful Termination:
-Always use onDestroy() to release resources. Failing to stop background tasks can
lead to memory leaks and performance degradation.
-For bound services, ensure proper cleanup when clients unbind by monitoring the
onUnbind() method and releasing any client-specific resources.
4. Restart Policies:
Set appropriate restart policies in onStartCommand() (START_STICKY,
START_NOT_STICKY, or START_REDELIVER_INTENT) depending on the
service’s purpose. For example, use START_STICKY for ongoing processes like
media playback, so the service restarts automatically if terminated.

3. Started Services in Android


A started service is initiated when an application component (e.g., an activity) calls
startService(). This service runs independently in the background and does not stop
unless explicitly stopped by the application or by the system. Commonly, started
services are used for:
1. Data Fetching: Periodically fetching data from a web service to keep information up
to date without interrupting the user.
2. File Uploads and Downloads: Downloading files or uploading user-generated
content to a server, essential for applications that work with media or large data files.
3. Location and Tracking Services: Services that run independently to keep track of
user location for mapping or navigation purposes.

Implementation-
One notable example is using a started service to fetch data from an API.
-For instance, a news application may use a started service to fetch and update the
latest news articles in the background, ensuring that the data is fresh without requiring
user intervention.A basic started service can be implemented with a standard Service
or IntentService class.
-An example
of how to implement a simple started service using IntentService to fetch data from a
web service.

import android.app.IntentService;
import android.content.Intent;
import android.util.Log;
public class FetchDataService extends IntentService {
private static final String TAG = "FetchDataService";
public FetchDataService() {
super("FetchDataService"); }
@Override protected void onHandleIntent(Intent intent) {
// Fetch data from a web service or API
try {
String data = fetchDataFromWebService();
Log.d(TAG, "Data fetched successfully: " + data);
// Process data or send a broadcast to update the UI
} catch (Exception e) {
Log.e(TAG, "Error fetching data", e); } } private String
fetchDataFromWebService() { // Simulate a network operation return "Sample data
from web service";
}
}
4.Bound Services in Android
Bound service is designed to act as an interface for clients to interact with and control
background tasks. Unlike started services, bound services do not operate indefinitely; they
typically run only while one or more clients are bound to them. Once all clients unbind from
the service, it is usually destroyed unless it has been started as well.
Common Scenarios for Bound Services:
1. Music Playback: Allowing users to control media playback (play, pause, skip) with
continuous feedback on track progress.
2. Real-Time Data Feeds: Providing real-time data updates from sensors, GPS tracking,
or live financial data.
3. Long-Running Data Processing: Handling tasks that require interaction with the user
or provide ongoing updates, like file downloads with progress reports.
Android provides two main mechanisms for implementing bound services: Binder
(for direct communication within the same process) and Messenger (for inter-process
communication or IPC).

Implementation-
Android provides two main mechanisms for implementing bound services: Binder
(for direct communication within the same process) and Messenger (for inter-process
communication or IPC).
An example of Creating a Bound Service Using Binder

Step 1: Define the service and extend the Binder class-


import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
public class MyBoundService extends Service {
// Binder given to clients private final IBinder binder = new LocalBinder();
// Class used for the client Binder public class LocalBinder extends Binder
{ MyBoundService getService() {
return MyBoundService.this;
}
}
@Override public IBinder onBind(Intent intent) {
return binder;
}
public int getRandomNumber() {
return (int) (Math.random() * 100);
}
}

Step 2: Bind to the service from an activity-


import android.content.ComponentName;
import android.content.Context;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
MyBoundService mService;
boolean mBound = false;
}
}
@Override protected void onStart() {
super.onStart();
Intent intent = new Intent(this, MyBoundService.class);
bindService(intent, connection, Context.BIND_AUTO_CREATE);
}
@Override protected void onStop() {
super.onStop();
if (mBound) {
unbindService(connection);
mBound = false;
}
}
}
5.Communication with Web Services in Android
Effective communication with web services is essential for modern Android
applications, allowing them to interact with external data sources, fetch updates, and
post data to remote servers. This process typically involves making HTTP/HTTPS
requests to RESTful APIs, retrieving and parsing responses (often in JSON or XML),
and handling data in a way that enhances user experience.

5.1 HTTP Client Communication-


HTTP (Hypertext Transfer Protocol) is a widely used protocol for exchanging data
between clients (such as Android devices) and servers over the web. HTTPS is the
secure version of HTTP, encrypting data to protect against eavesdropping and
tampering. Android provides several configurations for HTTP communication,
including handling SSL certificates and secure sockets for encrypted data transfer.
To communicate with a server, Android apps typically use either
HttpURLConnection, OkHttp, or Retrofit libraries to handle requests. Proper
configuration and error handling are necessary to ensure smooth communication with
web servers.

5.2 Overview of HTTP Clients in Android-


1. Apache HTTP Client: This client was popular in earlier Android versions but has
been deprecated since API level 23 (Android 6.0). It is not recommended for new
Android projects due to limited support and updates.
2. HttpURLConnection: This is the native Java HTTP client, which is lightweight and
straightforward for making HTTP requests. It is part of the Android SDK and is
suitable for simple HTTP operations, such as GET and POST requests.
3. OkHttp: A powerful and flexible HTTP client created by Square, OkHttp supports
synchronous and asynchronous requests, connection pooling, GZIP compression, and
caching. It’s highly efficient for handling complex HTTP operations, such as large file
uploads, downloads, and streaming data.
4. Retrofit: Retrofit is a high-level, type-safe HTTP client for Android, also developed
by Square. It uses OkHttp as its core but provides additional features, including
support for JSON and XML parsing, request/response serialization, and automatic
mapping of server responses to Java objects. Retrofit is widely used for REST API
communication due to its ease of use and strong integration with Gson and Moshi for
JSON parsing.
5.3 RESTful Web Services and Android-
REST (Representational State Transfer) is an architectural style for building
networked applications, where data can be transferred in a stateless manner. REST
APIs typically use HTTP methods (GET, POST, PUT, DELETE) to perform
operations on resources identified by URLs. Android apps can use REST APIs to
interact with backend services efficiently and reliably.

Principles of REST API:


 Statelessness: Each API call is independent and doesn’t rely on any previous state.
 Client-Server Architecture: The client (Android app) and the server (API backend)
are separate, allowing flexibility and scalability.
 Resource-Based URIs: Resources are accessible using URIs, and HTTP methods
dictate the action performed on those resources.
 Format Independence: Data formats (often JSON or XML) should be easily
readable by clients.

5.4 XML and JSON Data Handling-


Handling data from web services often involves parsing XML or JSON, as these are the
most common formats for data interchange in REST APIs.
Parsing XML Data
For XML, Android offers three main parsers:
1. DOM Parser: Parses the entire XML document at once, creating an in-memory tree
structure. It’s memory-intensive and generally slower, best suited for small XML files.
2. SAX Parser: A sequential parser that reads data element by element, which is
efficient for large XML documents but requires more code for event-based parsing.

3. XmlPullParser: A streaming parser that’s efficient for mobile use, allowing XML
data to be read in small chunks without loading the whole document into memory.
Parsing JSON Data
JSON (JavaScript Object Notation) is widely preferred over XML due to its
lightweight and easily readable structure.
Parsing JSON with Libraries:
1. JSONObject: Native JSON library in Android, good for basic JSON parsing.
2. Gson: A powerful library from Google for converting JSON to Java objects and vice
versa. Ideal for complex data models and arrays.
3. Moshi: A JSON library developed by Square, designed to work with Kotlin as well as
Java, providing high-speed and efficient parsing.

6.Preparing for Publishing an Android Application


Publishing an Android application involves several crucial steps to ensure that the app is
optimized for performance, provides a good user experience, and maintains security. This
section covers best practices for preparing graphics, optimizing network communication, and
ensuring security before releasing the application to the Google Play Store.

6.1 Preparing Graphics-


Visual assets are critical in providing a positive user experience. Proper preparation of
graphics is essential for ensuring that they look good across a variety of device resolutions
and screen sizes.
Best Practices for Optimizing Images and Graphics
1. Use Vector Drawables
2. Multiple Density Resources
3. Image Compression
4. Lazy Loading
5. Testing on Multiple Devices

6.2 Network Optimization-


Efficient network communication is essential for the performance of an Android application,
particularly when dealing with data-intensive operations. Optimizing network communication
can significantly enhance user experience, especially on devices with varying connectivity
speeds.
1. Use Background Threads:Always perform network operations in a background
thread to prevent UI blocking. Use AsyncTask, Handler, or Executors, or libraries like
Retrofit, which handle threading automatically.
2. Minimize Data Usage:Reduce the amount of data sent over the network. Use
efficient data formats (like JSON over XML) and ensure that only necessary data is
fetched from the server.Implement pagination or lazy loading when fetching large
datasets to avoid downloading unnecessary data all at once.
3. Caching:Implement caching strategies to minimize network requests:
 Disk Caching: Cache responses on the disk for future use. Libraries like OkHttp and
Retrofit have built-in support for caching.
 Memory Caching: Cache responses in memory to speed up subsequent requests.Set
appropriate cache expiration times to ensure users receive the most up-to-date
information.
4. Network Retry Mechanism:Implement retry mechanisms to handle transient
network issues gracefully. Use exponential backoff strategies to avoid overwhelming
the server with repeated requests.
5. API Rate Limiting:Respect API rate limits set by third-party services to avoid
service interruptions. Monitor network usage and implement backoff strategies when
approaching limits.

6.3 Security-
Security is paramount when dealing with user data and network communication.
Implementing robust security measures ensures that user information is protected
from unauthorized access.
1. SSL/TLS:
o Use SSL (Secure Sockets Layer) or TLS (Transport Layer Security) protocols
to encrypt data transmitted between the app and the server. This prevents
eavesdropping and man-in-the-middle attacks.
2. Certificate Pinning:
Implement certificate pinning to further secure communications.
This process involves hardcoding the server's public certificate in the app, ensuring that the
app only communicates with trusted servers.Certificate pinning can be implemented using
libraries like OkHttp, which provides built-in support for this feature.
7.Publishing to the Android Market (Google Play)
Publishing an Android application on the Google Play Store is a critical step in making it
available to users worldwide. This process involves meeting specific requirements,
preparing app listings effectively, and ensuring thorough testing before deployment. This
section outlines the essential aspects of publishing an app to Google Play, including
mandatory requirements, listing preparation, and final testing.

7.1 Google Play Requirements-


Before an app can be published on Google Play, developers must adhere to several
mandatory requirements set forth by Google. Understanding these requirements is crucial
for a successful app launch.
1. Privacy Policies- All apps that collect user data must have a privacy policy that
discloses how user information is collected, used, and shared. This policy must be
accessible both within the app and on the Play Store listing. A clear privacy policy fosters
trust among users, reassuring them that their data is handled responsibly.
2. Network Permissions- Apps that access the internet or use network features must
request the appropriate permissions in the AndroidManifest.xml file. This includes
permissions like INTERNET, ACCESS_NETWORK_STATE, or any other relevant
permissions.It is crucial to provide a rationale for the requested permissions, especially
for sensitive permissions like location access or storage access, as users can be cautious
about granting them.
3. Data Usage DisclosureTransparent Communication: Developers must inform users
about the data usage involved in the app, especially if the app uses a significant amount of
data or has features that impact the user’s data plan.Billing Considerations: If the app
includes any in-app purchases or subscription services, developers need to disclose this
information to ensure users are aware of potential charges.
4. Adherence to Content Policies-All apps must comply with Google Play’s Developer
Program Policies, which prohibit content that is inappropriate, misleading, or
harmful.Apps must have age ratings to ensure they are appropriate for the intended
audience.
7.2 App Listing Preparation-
Creating a compelling app listing on Google Play is essential for attracting users and
encouraging downloads. Here are the steps to prepare an effective app listing:
1. Set Up a Developer Account-Developers must create a Google Play Developer
account, which requires a one-time registration fee. This account allows developers to
publish apps, manage listings, and track performance metrics.Familiarize yourself with
the Google Play Console, where developers can manage all aspects of their apps,
including updates, reviews, and monetization.
2. Prepare App Descriptions-Choose a concise, descriptive title that reflects the app’s
functionality and is easy to remember. Write a brief, engaging summary of the app that
captures its main features and benefits, typically limited to 80 characters.Provide a
detailed description (up to 4,000 characters) that elaborates on the app’s functionality,
unique features, and potential use cases. Use relevant keywords to enhance search
visibility without resorting to keyword stuffing.
3. Create High-Quality Screenshots and Icons-Include at least 2-8 high-quality
screenshots demonstrating the app’s user interface and functionality. Screenshots should
highlight key features and user experiences.Prepare promotional images (e.g., banners or
feature graphics) that visually communicate the app’s value. These images can enhance
the app’s appeal on the Play Store.Design an eye-catching app icon that represents the
app’s branding and functionality. The icon should be simple yet distinctive, maintaining a
resolution of 512 x 512 pixels.

7.3 Final Testing and Deployment-


Thorough testing is vital before launching an app to ensure a smooth user experience. The
final testing phase should focus on usability, performance, and network-dependent
features.
1. Pre-launch Testing- Use Google Play's internal testing feature to distribute the app to
a small group of testers. This allows developers to gather feedback, identify bugs, and
ensure that the app functions as intended.Create a closed testing track to invite a limited
number of users to test the app. Collect feedback regarding usability, performance, and
any encountered issues.
2. Test on Various Devices and Networks- Ensure that the app runs smoothly on a
variety of devices with different screen sizes, resolutions, and hardware
specifications.Test the app under various network conditions (e.g., Wi-Fi, 4G, 3G, and
offline scenarios) to evaluate its performance and responsiveness. Implement techniques
like caching and background data processing to enhance user experience in low-
connectivity situations.
3. Monitor App Performance Post-Launch- Integrate analytics tools (like Firebase
Analytics) to track user engagement, app performance, and error reports. This information
is invaluable for ongoing optimization.After launching the app, monitor user reviews and
ratings on the Google Play Store. Promptly address any reported issues and consider user
feedback for future updates.

Conclusion

The development and publishing of an Android application encompass a


series of critical steps that require careful consideration and execution. This
comprehensive report has provided an in-depth exploration of key
components, including Android services, their lifecycle, types of services,
communication with web services, preparation for publishing, and final
testing strategies.
1. Android Services
2. Efficient Communication with Web Services
3. Publishing and Preparing for Launch
4. Commitment to Continuous Improvement
In conclusion, the process of developing and publishing an Android
application is complex but rewarding. By adhering to the best practices
outlined in this report, developers can create efficient, user-friendly
applications that stand out in the dynamic mobile app landscape. The
successful deployment and maintenance of an app require ongoing
commitment and a proactive approach to enhancement and user engagement,
ultimately leading to sustained growth and user loyalty.
References
[1] Suh, Y., H. Lee, and Y. Park. 2012. Analysis and Visualisation of
Structure of Smartphone Application Services Using Text Mining and the
Set-Covering Algorithm: A Case of App Store. International Journal of
Mobile Communications. 10(1): 1–20.
[2] Murray, K. B., J. Liang, and G. Haubl. 2010. ACT 2.0: The Next
Generation of Assistive Consumer Technology Research. Internet
Research. 20(3): 232–254.
[3] Kimbler, K. 2010. App Store Strategies for Service Providers.
Proceedings in 14th International Conference on Intelligence in Next
Generation Networks (ICIN).
[4] White, M. 2010. Information Anywhere, Any When: The Role of the
Smartphone. Business Information Review. 27(4): 242–247.
[5] Holzer, A., and J. Ondrus. 2011. Mobile Application Market: A
Developer’s Perspective. Telematics and Informatics. 28(1): 22–31.
[6] Müller, R. M., B. Kijl, and J. K. J. Martens. 2011. A Comparison of
Inter-Organizational Business Models of Mobile App Stores: There Is
More Than Open Vs. Closed. Journal of Theoretical and Applied
Electronic Commerce Research. 6(2): 63–76.
[7] Verkasalo, H., C. López-Nicolás, F. J. Molina-Castillo, and H.
Bouwman. 2010. Analysis of Users and Non-Users of Smartphone
Application

You might also like