Unit 2 (Android)
Unit 2 (Android)
Prof.Rahul Khandarkar
Android Programming
UI layer architecture
The term UI refers to UI elements such as activities and fragments that display the data,
independent because the role of the data layer is to hold, manage, and provide access to the
app data, the UI layer must perform the following steps:
1. Consume app data and transform it into data the UI can easily render.
2. Consume UI-renderable data and transform it into UI elements for presentation to the
user.
3. Consume user input events from those assembled UI elements and reflect their effects
in the UI data as needed.
4. Repeat steps 1 through 3 for as long as necessary.
The rest of this guide demonstrates how to implement a UI layer that performs these steps. In
particular, this guide covers the following tasks and concepts:
Prof.Rahul Khandarkar
Android Programming
Define UI state
In short, the UI shows a list of articles along with some metadata for each article. This
information that the app presents to the user is the UI state.
In other words: if the UI is what the user sees, the UI state is what the app says they should
see. Like two sides of the same coin, the UI is the visual representation of the UI state. Any
changes to the UI state are immediately reflected in the UI.
State holders
• The classes that are responsible for the production of UI state and contain the
necessary logic for that task are called state holders. State holders come in a variety of
sizes depending on the scope of the corresponding UI elements that they manage,
ranging from a single widget like a bottom app bar to a whole screen or a navigation
destination.
• There are many ways to model the codependency between the UI and its state
producer. However, because the interaction between the UI and its View Model class
Prof.Rahul Khandarkar
Android Programming
can largely be understood as event input and its ensuing state output, the relationship
can be represented as shown in the following diagram:
The pattern where the state flows down and the events flow up is called a
unidirectional data flow (UDF). The implications of this pattern for app
architecture are as follows:
The View Model holds and exposes the state to be consumed by the UI. The UI
state is application data transformed by the View Model.
The UI notifies the View Model of user events.
The View Model handles the user actions and updates the state.
The updated state is fed back to the UI to render.
The above is repeated for any event that causes a mutation of state.
Prof.Rahul Khandarkar
Android Programming
• A user requesting to bookmark an article is an example of an event that can cause state
mutations. As the state producer, it's the View Model’s responsibility to define all the
logic required in order to populate all fields in the UI state and process the events
needed for the UI to render fully.
Prof.Rahul Khandarkar
Android Programming
Context
Android Applications are popular for a long time and it is evolving to a greater level
as users’ expectations are that they need to view the data that they want in an easier smoother
view. Hence, the android developers must know the important terminologies before
developing the app. In Android Programming we generally come across the word Context.
So what exactly is this Context and why is it so important? To answer this question let’s first
see what the literal meaning of Context is:
The Circumstances that form the setting for an Event, Statement, or Idea, and in terms of
which it can be fully understood.
The Context tells us about the surrounding information.
It is very important to understand the environment which we want to understand.
Let’s a person visit a hotel. He needs breakfast, lunch, and dinner at a suitable time.
Except for these things there are also many other things, he wants to do during his time of
stay. So how does he get these things? He will ask the room-service person to bring these
things for him. Right? So here the room-service person is the Context considering you are
the single activity and the hotel to be your app, finally, the breakfast, lunch & dinner
have to be the resources.
Prof.Rahul Khandarkar
Android Programming
4. Both the Activity and Application classes extend the Context class.
In android, Context is the main important concept and the wrong usage of it leads to
memory leakage. Activity refers to an individual screen and Application refers to the whole
app and both extend the Context class.
It can be seen in the above image that in “Sample Application”, the nearest Context is
Application Context. In “Activity1” and “Activity2”, both Activity Context (Here it is
Activity1 Context for Activity1 and Activity2 Context for Activity2) and Application
Context. The nearest Context to both is their Activity Context only.
Prof.Rahul Khandarkar
Android Programming
1. Application Context:
• getApplicationContext():
It is used to return the Context which is linked to the Application which holds all
activities running inside it. When we call a method or a constructor, we often have to pass a
Context and often we use “this” to pass the activity Context or “getApplicationContext” to
pass the application Context. This method is generally used for the application level and can
be used to refer to all the activities. For example, if we want to access a variable throughout
the android app, one has to use it via getApplicationContext().
import android.app.Application;
return globalName;
globalName = aName;
return globalEmail;
Prof.Rahul Khandarkar
Android Programming
globalEmail = aEmail;
Inside the activity class, set the name and email of GlobalExampleClass, which can be
accessed from another activity. Let us see via the below steps.
// Activity 1
public class <your activity1> extends Activity {
........
........
private <yourapplicationname> globarVar;
........
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable = (GlobalExampleClass)
getApplicationContext();
// In this activity set name and email and can reuse in other activities
globalExampleVariable.setName("getApplicationContext example");
globalExampleVariable.setEmail("[email protected]");
.......
}
// Activity 2
public class <your activity2> extends Activity {
........
........
private <yourapplicationname> globarVar;
.......
Prof.Rahul Khandarkar
Android Programming
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable = (GlobalExampleClass)
getApplicationContext();
// As in activity1, name and email is set, we can retrieve it here
So, whenever the variable scope is required throughout the application, we can get it by
means of getApplicationContext(). Following is a list of functionalities of Application
Context.
2. Activity Context:
It is the activity Context meaning each and every screen got an activity. For example,
EnquiryActivity refers to EnquiryActivity only and AddActivity refers to AddActivity only.
It is tied to the life cycle of activity. It is used for the current Context. The method of invoking
the Activity Context is getContext().
Prof.Rahul Khandarkar
Android Programming
• getContext():
It returns the Context which is linked to the Activity from which it is called. This is
useful when we want to call the Context from only the current running activity.
Example:
@Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
// view.getContext() refers to the current activity view
// Here it is used to start the activity
Intent intent = new Intent(view.getContext(), <your java classname>::class.java);
intent.putExtra(pid, ID);
view.getContext().startActivity(intent);
}
From the functionalities of both Application and Activity, we can see that the difference
is that the Application Context is not related to UI. It should be used only to start a service
or load resource values etc. Apart from getApplicationContext() and
getContext(), getBaseContext() or this are the different terminologies used throughout the
app development. Let us see with an example,
• getBaseContext():
The base Context is set by the constructor or setBaseContext().This method is only
valid if we have a ContextWrapper. Android provides a ContextWrapper class that is
created around an existing Context using:
Prof.Rahul Khandarkar
Android Programming
Syntax:
this:
“this” argument is of a type “Context”. To explain this Context let’s take an example to
show a Toast Message using “this”.
Example:
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
// Show a simple toast message, that can be done after doing some activities
// Toast.makeText(this, "Action got completed", Toast.LENGTH_SHORT).show();
Prof.Rahul Khandarkar
Android Programming
public class ExampleActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_example);
// Displaying Toast with Hello Javatpoint message
Toast.makeText(this,"Action done",Toast.LENGTH_SHORT).show();
}
}
Intent:
In Android, it is quite usual for users to witness a jump from one application to another
as a part of the whole process, for example, searching for a location on the browser and
witnessing a direct jump into Google Maps or receiving payment links in Messages
Application (SMS) and on clicking jumping to PayPal or GPay (Google Pay). This process
of taking users from one application to another is achieved by passing the Intent to the
system. Intents, in general, are used for navigating among various activities within the same
application, but note, is not limited to one single application, i.e., they can be utilized from
moving from one application to another as well.
Intents could be Implicit, for instance, calling intended actions, and explicit as well, such
as opening another activity after some operations like onClick or anything else. Below are
some applications of Intents:
Prof.Rahul Khandarkar
Android Programming
Implicit Intent: - Implicit Intent doesn’t specify the component. In such a case, intent
provides information on available components provided by the system that is to be invoked.
Prof.Rahul Khandarkar
Android Programming
Explicit Intent
Explicit Intent specifies the component. In such a case, intent provides the external
class to be invoked.
For Example: In the below example, there are two activities (FirstActivity, and
SecondActivity). When you click on the ‘GO TO OTHER ACTIVITY’ Button in the
FirstActivity, then you move to the SecondActivity. When you click on the ‘GO TO HOME
ACTIVITY’ button in the SecondActivity, then you move to the first activity. This is
getting done through Explicit Intent.
Prof.Rahul Khandarkar
Android Programming
There's nothing special about the Intent object you use when starting an activity for a
result, but you do need to pass an additional integer argument to
the startActivityForResult() method.
The integer argument is a "request code" that identifies your request. When you
receive the result Intent, the callback provides the same request code so that your app can
properly identify the result and determine how to handle it.
For example, here's how to start an activity that allows the user to pick a contact:
Prof.Rahul Khandarkar
Android Programming
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
In this example, the result Intent returned by Android's Contacts or People app
provides a content Uri that identifies the contact the user selected.
In order to successfully handle the result, you must understand what the format of the
result Intent will be. Doing so is easy when the activity returning a result is one of your own
activities. Apps included with the Android platform offer their own APIs that you can count
on for specific result data. For instance, the People app (Contacts app on some older
versions) always returns a result with the content URI that identifies the selected contact, and
the Camera app returns a Bitmap in the "data" extra (see the class about Capturing Photos).
Prof.Rahul Khandarkar
Android Programming
Intent filters and intent resolution
Intent Filter
Implicit intent uses the intent filter to serve the user request.
The intent filter specifies the types of intents that an activity, service, or broadcast receiver
can respond.
Intent filters are declared in the Android manifest file.
Intent filter must contain <action>
<intent-filter
android:icon="drawable resource"
android:label="string resource"
android:priority="integer" >
...
</intent-filter>
1. <action>
<action android:name="string" />
Adds an action to an intent filter. An <intent-filter> element must contain one or
more <action> elements. If there are no <action> elements in an intent filter, the filter
doesn’t accept any Intent objects.
Examples of common action:
ACTION_VIEW: Use this action in intent with startActivity() when you have some
information that activity can show to the user like showing an image in a gallery app
or an address to view in a map app
ACTION_SEND: You should use this in intent with startActivity() when you have
some data that the user can share through another app, such as an email app or social
sharing app.
Prof.Rahul Khandarkar
Android Programming
2. <category>
<category android:name="string" />
Adds a category name to an intent filter. A string containing additional information about the
kind of component that should handle the intent.
Example of common categories:
3. <data>
Syntax:
<data android:scheme="string"
android:host="string"
android:port="string"
android:path="string"
android:pathPattern="string"
android:pathPrefix="string"
android:mimeType="string" />
Adds a data specification to an intent filter. The specification can be just a data type, just a
URI, or both a data type and a URI.
(Uniform Resource Identifier (URI) is a string of characters used to identify a resource.
A URI identifies a resource either by location, or a name, or both.)
It defines the type of data to be accepted and by using one or more attributes we can specify
various aspects of the data URI (scheme, host, port, path) and MIME type.
Prof.Rahul Khandarkar
Android Programming
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
We can define a filter with multiple instances of <action>, <category> or <data> elements
and we need to make sure that component can handle all the combinations of filter elements.
If you observe above code snippet the activity “MainActivity” will act as an entry
point for our app because we defined an activity using MAIN action
and LAUNCHER category attributes in intent filters (<intent-filter>).
MAIN - It indicates the app’s main entry point that means it starts the activity which defines
with the MAIN action when the user initially launches the app with a launcher icon.
LAUNCHER - It indicates that this activity icon should be placed on the home screen list of
apps. In case if the <activity> element doesn’t specify an icon with icon, then the system
uses the icon from the <application> element.
These two (MAIN, LAUNCHER) elements must be paired together in order for the activity
to appear in the app launcher.
The second activity “ResultActivity” is intended to help us to share the text. The user might
enter this activity by navigating from MainActivity and they can also enter directly from
another app using Implicit Intent which is matching one of the two activity filters.
Create a new android application using android studio and open an activity_main.xml file
from \src\main\res\layout path.
Prof.Rahul Khandarkar
Android Programming
activity_main.xml
MainActivity.java
package com.tutlane.intentfilters;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnSend = (Button)findViewById(R.id.sendMail);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent si = new Intent(Intent.ACTION_SEND);
si.setType("message/rfc822");
si.putExtra(Intent.EXTRA_EMAIL, new String[]{"[email protected]"});
si.putExtra(Intent.EXTRA_SUBJECT, "Welcome to Tutlane");
si.putExtra(Intent.EXTRA_TEXT, "Hi Guest, Welcome to Tutlane Tutorial
Site");
startActivity(Intent.createChooser(si,"Choose Mail App"));
}
});
}
}
If you observe above code we used multiple components to send email, those are
si - Our local implicit intent
ACTION_SEND - It’s an activity action that specifies that we are sending some data.
setType - We use this property to set the MIME type of data that we want to send. Here we
used “message/rfc822” and other MIME types are “text/plain” and “image/jpg”
AndroidManifest.xml
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="message/rfc822"/>
</intent-filter>
</activity>
</application>
</manifest>
If you observe above AndroidManifest.xml file we added following extra fields of Intent
filters.
category - we included the DEFAULT category for this activity to be able to receive implicit
intents.
Intent resolution
The Intent Resolution compares the contents of Intent Object against the Intent Filters.
(Intent Filters are associated with the different Android components, and can receive Intent.
Intent filter is a way for Android components to declare their capabilities to the Android
system.)
• The intent transfer process has two ways to match target consumers (such as another activity,
IntentReceiver, or service) with the respondents of the intent.
• In explicit matching, when constructing an intent object, you must specify the recipient as
one of the intent's component properties.
• In implicit matching, the sender of the intent does not know or care who the recipient is when
constructing an intent object.
• Because of the arbitrary (random choice) nature of Implicit Intents, the system uses a process
called Intent Resolution to map them correctly.
• The system does this by matching the Intent description with the default descriptions in the
system.
• The Intent Resolution compares the contents of Intent Object against the Intent Filters.
• Intent Filters are associated with the different Android components, and can receive Intent.
• Intent filter is a way for Android components to declare their capabilities to the Android
system.
• Filters play an important role in defining the kind of intent an Android component can
receive.
The Intent Resolution uses the following information to map the Intent to the appropriate
Android component:
• The action
• The type (data type and URI)
Prof. Manasi Talele 25
Android Programming
• The category
• Action: Declares the intent action accepted, in the name attribute. The value must be the
literal string value of an action, not the class constant.
• Data: Declares the type of data accepted, using one or more attributes that specify various
aspects of the data URI (scheme, host, port, and path) and MIME type.
• Category: Declares the intent category accepted, in the name attribute. The value must be
the literal string value of an action, not the class constant.
Implicit intents in Android are used to request functionality from other components of
the Android system or other installed applications without specifying the exact component to
be invoked. Instead, the system looks for the appropriate component that can handle the
specified action or data.
Here are some common applications of implicit intents in Android:
1. Opening a Web Page:
This implicit intent opens a web page using the default web browser.
This implicit intent opens the dialer with the specified phone number.
3. Opening URLs:
Implicit intents are commonly used to open web pages or specific URLs. By using the
Intent.ACTION_VIEW action and providing a URL as a Uri.
Implicit intents can be employed to open a map application for navigation to a specific
location using geo-coordinates.
Implicit intents are useful for composing and sending emails or text messages. By using
the Intent.ACTION_SENDTO action, you can launch the appropriate application for
communication.
6. Sharing Content:
Implicit intents can be employed to open the camera or gallery apps for capturing photos
or selecting images. This is often done using the MediaStore and Intent.ACTION_PICK
or Intent.ACTION_IMAGE_CAPTURE actions.
Implicit intents can be used to play media files, such as audio or video. By specifying
the Intent.ACTION_VIEW action and providing the URI of the media file, you can let
the system choose an appropriate application for playback.
Activity stack
• When doing a job, users engage with a task, which is a set of actions
• The activities are stacked in the order in which they are opened in a stack called the back
stack.
• For example, in an email app, there is one action to display a list of fresh messages, when
the user picks a message, a new activity appears in which the user may read the message.
• This new action has been sent to the back of the queue.
• When the user clicks the Back button, the new action is completed and removed from the
stack.
• When numerous applications are running in a multi-windowed environment, the system
maintains tasks for each window individually; each window may contain several tasks.
For most tasks, the device’s home screen is the starting point.
• The work of an app is brought to the front when the user taps an icon in the app launcher
• If no task for the app exists (because it hasn’t been used recently), a new task is created, and
the app’s “main” activity is opened as the stack’s root activity.
• When the current activity switches to a new one, the new activity is pushed to the top of the
stack and takes control of the attention.
• The preceding action is still there in the stack, but it is no longer active
• When a task is completed, the system saves the current state of the user interface.
• The current activity is destroyed) when the user hits the Back button and the prior activity
restarts (the previous state of its UI is restored
• the back stack is an object structure that is “last in, first out”
• A task can then be brought back into the “foreground,” allowing users to resume their work
where they left off.
• Assume that the current task (Task A) contains three activities in its stack, two of which are
underneath the current activity.
• The user hits the Home button, then opens the app launcher and selects a new app.
• Task A is pushed to the background when the Home screen appears.
• When a new app is launched, the system creates a task (Task B) for it, which has its own set
of activities.
• After interacting with that app, the user goes back to Home and picks the app that launched
Task A in the first place.
• Task A now appears in the forefront, with all three activities in its stack intact and the activity
at the top of the stack resumed.
• The user may now return to Task B by navigating to Home and choosing the app icon that
initiated the task.
• On Android, this is an example of multitasking.
• Because the activities in the back stack are never reorganized if your app allows users to
launch a specific activity from multiple activities, a new instance of that activity is produced
and placed onto the stack.
• As a result, a single activity in your app may be invoked many times.
• As a result, if the user uses the Back button to browse backward, each instance of the activity
will be presented in the sequence in which it was accessed.
• If you don’t want an activity to be created more than once, however, you may change this
behaviour
To describe the default behaviour for activities and tasks, consider the following:
• Activity A is interrupted when Activity B begins, but the system’s state is preserved (such as
scroll position and text entered into forms). When the user returns to Activity A after pressing
the Back button in Activity B, the state of Activity A is restored.
• When a user exits a task by hitting the Home button, the present activity is terminated and
the task is placed in the background. Every activity in the task is saved in the system’s memory.
The task comes to the foreground and resumes the activity at the top of the stack if the user
subsequently continues it by clicking the launcher icon that started it in the first place.
• The current activity is removed from the stack and deleted when the user hits the Back button.
In the stack, the prior action is resumed. The system does not keep track of the status of activity
when it is deleted. Even from other tasks, activities can be instantiated several times.
1. Foreground process
• A foreground process is a process with which the user is currently interacting and using it.
• A process is considered to be in the foreground state if any of the below conditions hold:
If the process is running an activity with which the user is interacting
If it has a broadcast receiver which is currently in execution to receive any system
update.
Example: Imagine the user is using Whatsapp, so the Whatsapp app will be said to be in the
foreground state. This process is of the highest priority and they can only be killed by the
system if the memory is so low that even this process cannot continue their execution.
2. Visible process
• A visible process is a process when the activity can be visible to the user.
• The user does not directly interact with this process, as the activity corresponds to this process
would be covered partially by another activity and the process will be in the onPause() lifecycle
state
• This process cannot be killed if there is so much lack of memory in the system that the
execution of these processes cannot be possible.
• Killing these processes will create a negative impact on user experience, as a user can see
the activity corresponding to this process.
3. Service Pro
• A process is said to be a service process if it is in running state and neither a foreground
process and a visible processes
• These processes are not directly visible to the user of the application
• This process is helpful for the applications which perform the background tasks such as
background network data upload or download.
• The system will keep the service process alive until it becomes impossible for the system to
keep the foreground process and visible process running.
• Example: Uploading a PDF on the Whatsapp from the desktop is a service process that is
done in the background.
4. Background process
• A background state in which the onStop() lifecycle method of android is called by the system
• Let’s suppose the user is using an app and suddenly presses the home button, so because of
this action, the process goes from foreground state to background state.
• When the app goes from foreground state to background state, it goes to the LRU cache
queue and will be placed in the front of the queue.
• When the user returns to that app, the process will return from background state to foreground
state • So having knowledge of the process and application lifecycle in android along with how
processes can decide the lifecycle time of the application is a must for an android developer
which can lead to good user experience.
Each fragment has its own lifecycle but due to the connection with the Activity it belongs to,
the fragment lifecycle is influenced by the activity’s lifecycle.
2. Dynamically:
FragmentManager is used to embed fragments with activities that enable the
addition, deletion, or replacement of fragments at run time