Android Development: Key Components and Concepts
AndroidManifest.xml – Describe your app in this file; your app starts with the “main” method you declare here. You also need to declare all of your activities here.
Activity – An Activity
is a Java controller class that typically corresponds to one screen in your app.
Fragment – A Fragment
is a Java controller that typically corresponds to a widget in a screen (or possibly the full screen).
Intent – You launch new activities with Intents.
Service – Background services, like notifications.
R
class – Generated for you by the Android build process.
Content Providers − It will share the data between applications.
View – Widgets like TextView, ImageView, Button.
ViewGroup – Containers for other views.
Layouts: FrameLayout, LinearLayout, RelativeLayout, TableLayout, ListView, GridView.
Application The Application class in Android is the base class within an Android app that contains all other components such as activities and services. The Application class, or any subclass of the Application class, is instantiated before any other class when the process for your application/package is created.
Contextis a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. An Android app has activities. Context is like a handle to the environment your application is currently running in:
Application Context:This context is tied to the lifecycle of an application. The application context can be used where you need a context whose lifecycle is separate from the current context or when you are passing a context beyond the scope of an activity.
Activity Context: This context is available in an activity. This context is tied to the lifecycle of an activity. The activity context should be used when you are passing the context in the scope of an activity or you need the context whose lifecycle is attached to the current context.
A Service
is an application component that can perform long-running operations in the background, and it doesn’t provide a user interface. It can run in the background, even when the user is not interacting with your application. These are the three different types of services:
- Foreground Service: A foreground service performs some operation that is noticeable to the user. For example, we can use a foreground service to play an audio track. A Notification must be displayed to the user.
- Background Service: A background service performs an operation that isn’t directly noticed by the user. In Android API level 26 and above, there are restrictions to using background services and it is recommended to use WorkManager in these cases.
- Bound Service: A service is bound when an application component binds to it by calling
bindService()
. A bound service offers a client-server interface that allows components to interact with the service, send requests, receive results. A bound service runs only as long as another application component is bound to it.
Difference between Service & Intent Service
- Service is the base class for Android services that can be extended to create any service. A class that directly extends Service runs on the main thread so it will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for longer tasks.
- IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
Difference between AsyncTasks & Threads?
- Thread should be used to separate long running operations from main thread so that performance is improved. But it can’t be cancelled elegantly and it can’t handle configuration changes of Android. You can’t update UI from Thread.
- AsyncTask can be used to handle work items shorter than 5ms in duration. With AsyncTask, you can update UI unlike java Thread. But many long running tasks will choke the performance.
Difference between Service, Intent Service, AsyncTask & Threads
- Android service is a component that is used to perform operations on the background such as playing music. It doesn’t has any UI (user interface). The service runs in the background indefinitely even if application is destroyed.
- AsyncTask allows you to perform asynchronous work on your user interface. It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
- IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.
- A thread is a single sequential flow of control within a program. Threads can be thought of as mini-processes running within a main process.
What are Handlers?
Handlers are objects for managing threads. It receives messages and writes code on how to handle the message. They run outside of the activity’s lifecycle, so they need to be cleaned up properly or else you will have thread leaks.
- Handlers allow communicating between the background thread and the main thread.
- A Handler class is preferred when we need to perform a background task repeatedly after every x seconds/minutes.
What is Job Scheduling?
Job Scheduling API, as the name suggests, allows to schedule jobs while letting the system optimize based on memory, power, and connectivity conditions. The JobScheduler supports batch scheduling of jobs. The Android system can combine jobs so that battery consumption is reduced. JobManager makes handling uploads easier as it handles automatically the unreliability of the network. It also survives application restarts. Some scenarios:
- Tasks that should be done once the device is connect to a power supply
- Tasks that require network access or a Wi-Fi connection.
- Task that are not critical or user facing
- Tasks that should be running on a regular basis as batch where the timing is not critical
- You can click on this link to learn more about Job Schedulers.
Android Bound Service
A bound service is a service that allows other android components (like activity) to bind to it and send and receive data. A bound service is a service that can be used not only by components running in the same process as local service, but activities and services, running in different processes, can bind to it and send and receive data.
- When implementing a bound service we have to extend Service class but we have to override onBind method too. This method returns an object that implements IBinder, that can be used to interact with the service.
Implementing Android bound service with Android Messenger
- Service based on Messenger can communicate with other components in different processes, known as Inter Process Communication (IPC), without using AIDL.
- A service handler: this component handles incoming requests from clients that interact with the service itself.
- A Messenger: this class is used to create an object implementing IBinder interface so that a client can interact with the service.
- Example Implementation: Link
AIDL vs Messenger Queue
- As Ariq Ahmad mentioned in the response, Messenger Queue builds us a queue and the data/messages are passed between 2 or more processes sequential. But in case of AIDL the messages are passed in parallel.
- AIDL is for the purpose when you’ve to go application level communication for data and control sharing, a scenario depicting it can be : An app requires list of all contacts from Contacts app (content part lies here) plus it also wants to show the call’s duration and you can also disconnect it from that app (control part lies here).
- In Messenger queues you’re more IN the application and working on threads and processes to manage the queue having messages so no Outside services interference here.
- Messenger is needed if you want to bind a remote service (e.g. running in another process).
What is a ThreadPool? And is it more effective than using several separate Threads?
Creating and destroying threads has a high CPU usage, so when we need to perform lots of small, simple tasks concurrently, the overhead of creating our own threads can take up a significant portion of the CPU cycles and severely affect the final response time. ThreadPool consists of a task queue and a group of worker threads, which allows it to run multiple parallel instances of a task.
Difference between Serializable and Parcelable?
Serialization is the process of converting an object into a stream of bytes in order to store an object into memory, so that it can be recreated at a later time, while still keeping the object’s original state and data.
How to disallow serialization? We can declare the variable as transient.
Serializable is a standard Java interface. Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable (The problem with this approach is that reflection is used and it is a slow process. This mechanism also tends to create a lot of temporary objects and cause quite a bit of garbage collection.).
Difference between Activity & Service
Activities are basically containers or windows to the user interface. Services is a component that is used to perform operations on the background. It does not have an UI.
How would you update the UI of an activity from a background service?
We need to register a LocalBroadcastReceiver in the activity. And send a broadcast with the data using intents from the background service. As long as the activity is in the foreground, the UI will be updated from the background. Ensure to unregister the broadcast receiver in the onStop() method of the activity to avoid memory leaks. We can also register a Handler and pass data using Handlers. You can find more details on how to implement here.
What is an intent?
Intents are messages that can be used to pass information to the various components of android. For instance, launch an activity, open a webview etc. Two types of intents-
- Implicit: Implicit intent is when you call system default intent like send email, send SMS, dial number.
- Explicit: Explicit intent is when you call an application activity from another activity of the same application.
Describe Fragment Lifecycle
onAttach()
: The fragment instance is associated with an activity instance.The fragment and the activity is not fully initialized. Typically you get in this method a reference to the activity which uses the fragment for further initialization work.onCreate()
: The system calls this method when creating the fragment. You should initialize essential components of the fragment that you want to retain when the fragment is paused or stopped, then resumed.onCreateView()
: The system calls this callback when it’s time for the fragment to draw its user interface for the first time. To draw a UI for your fragment, you must return a View component from this method that is the root of your fragment’s layout. You can return null if the fragment does not provide a UI.onActivityCreated()
: The onActivityCreated() is called after the onCreateView() method when the host activity is created. Activity and fragment instance have been created as well as the view hierarchy of the activity. At this point, view can be accessed with the findViewById() method. example. In this method you can instantiate objects which require a Context objectonStart()
: The onStart() method is called once the fragment gets visible.onResume()
: Fragment becomes active.onPause()
: The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session.onStop()
: Fragment going to be stopped by calling onStop()onDestroyView()
: Fragment view will destroy after call this methodonDestroy()
:called to do final clean up of the fragment’s state but Not guaranteed to be called by the Android platform.
Lifecycle of an Activity
OnCreate()
: This is when the view is first created. This is normally where we create views, get data from bundles etc.OnStart()
: Called when the activity is becoming visible to the user. Followed by onResume() if the activity comes to the foreground, or onStop() if it becomes hidden.OnResume()
: Called when the activity will start interacting with the user. At this point your activity is at the top of the activity stack, with user input going to it.OnPause()
: Called as part of the activity lifecycle when an activity is going into the background, but has not (yet) been killed.OnStop()
: Called when you are no longer visible to the user.OnDestroy()
: Called when the activity is finishingOnRestart()
: Called after your activity has been stopped, prior to it being started again
What is Android?
Android is an open-source and Linux-based OS for mobile devices such as smartphones and tablets. Android is a community of developers known as the Open Handset Alliance and commercially backed by Google. It was released in November 2007 and the first commercial Android device was introduced in September 2008.
We have approximately 2.3 Billion that is android based and are embraced by users all around the world. Needless to say that android is here to stay for years to come, and with the regular updates from Google, it is only going to grow gradually. Now that you know the importance of Android and other beneficial factors, let’s head on to start learning more about it.