Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
15 views39 pages

Unit 2 (Android)

The document covers Android programming concepts, focusing on User Interface (UI) architecture, including the role of the UI, activity life cycle, and the importance of context. It emphasizes the Unidirectional Data Flow (UDF) pattern for managing UI state and interactions, detailing the responsibilities of state holders and the relationship between UI and ViewModel. Additionally, it explains the two types of context in Android: Application Context and Activity Context, along with their functionalities and usage in app development.

Uploaded by

deveshvpatil20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views39 pages

Unit 2 (Android)

The document covers Android programming concepts, focusing on User Interface (UI) architecture, including the role of the UI, activity life cycle, and the importance of context. It emphasizes the Unidirectional Data Flow (UDF) pattern for managing UI state and interactions, detailing the responsibilities of state holders and the relationship between UI and ViewModel. Additionally, it explains the two types of context in Android: Application Context and Activity Context, along with their functionalities and usage in app development.

Uploaded by

deveshvpatil20
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Android Programming

Unit-2 User Interface Architecture


Syllabus:
 Application context
 Intents: explicit intents
o Returning results from activities
o Implicit intents
o Intent filters and intent resolution
o Applications of implicit intents
 Activity life cycle
o Activity stack
o Application’s priority and its process’ states
 Fragments and its life cycle.

User Interface Architecture


UI layer
The role of the UI is to display the application data on the screen and also to serve as
the primary point of user interaction. Whenever the data changes, either due to user interaction
(like pressing a button) or external input (like a network response), the UI should update to
reflect those changes.
Effectively, the UI is a visual representation of the application state as retrieved from the data
layer.
However, the application data you get from the data layer is usually in a different format
than the information you need to display. For example, you might only need part of the data
for the UI, or you might need to merge two different data sources to present information that
is relevant to the user. Regardless of the logic you apply, you need to pass the UI all the
information it needs to render fully. The UI layer is the pipeline that converts application data
changes to a form that the UI can present and then displays it.

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:

 How to define the UI state.


 Unidirectional data flow (UDF) as a means of producing and managing the UI state.
 How to expose UI state with observable data types according to UDF principles.
 How to implement UI that consumes the observable UI state.
 The most fundamental of these is the definition of the UI state.

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.

Manage state with Unidirectional Data Flow


• These interactions may benefit from a mediator to process them, defining the logic to
be applied to each event and performing the requisite transformations to the backing
data sources in order to create UI state. These interactions and their logic may be
housed in the UI itself, but this can quickly get unwieldy as the UI starts to become
more than its name suggests: it becomes data owner, producer, transformer, and more.
Furthermore, this can affect testability because the resulting code is a tightly coupled
amalgam with no discernable boundaries. Ultimately, the UI stands to benefit from
reduced burden. Unless the UI state is very simple, the UI's sole responsibility should
be to consume and display UI state.
• This section discusses Unidirectional Data Flow (UDF), an architecture pattern that
helps enforce this healthy separation of responsibility.

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.

 For navigation destinations or screens, the ViewModel works with repositories or


use case classes to get data and transform it into the UI state while incorporating
the effects of events that may cause mutations of the state. The case
study mentioned earlier contains a list of articles, each having a title, description,
source, author name, publication date, and whether it was bookmarked. The UI for
each article item looks like this:

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.

Why use UDF?


UDF models the cycle of state production as shown in Figure 4. It also separates the
place where state changes originate, the place where they are transformed, and the place
where they are finally consumed. This separation lets the UI do exactly what its name
implies: display information by observing state changes, and relay user intent by passing
those changes on to the ViewModel.
In other words, UDF allows for the following:
 Data consistency. There is a single source of truth for the UI.
 Testability. The source of state is isolated and therefore testable independent of the
UI.
 Maintainability. Mutation of state follows a well-defined pattern where mutations
are a result of both user events and the sources of data they pull from

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.

Similarly, when we talk about Android Programming Context can be understood as


something which gives us the Context of the current state of our application. We can break
the Context and its use into three major points:
 It allows us to access resources.
 It allows us to interact with other Android components by sending messages.
 It gives you information about your app environment.
The code has been given in both Java and Kotlin Programming Language for Android.

Understanding Context by a Real-World Example:

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.

How Does this Work?


1. It is the Context of the current/active state of the application.
Usually, the app got multiple screens like display/inquiry/add/delete screens (A
general requirement of a basic app). So when the user is searching for something, the Context
is an inquiry screen in this case.

Prof.Rahul Khandarkar
Android Programming

2. It is used to get information about the activity and application.


The inquiry screen’s Context specifies that the user is in inquiry activity, and he/she
can submit queries related to the app

3. It is used to get access to resources, databases, shared preferences, etc.


Via Rest services, API calls can be consumed in android apps. Rest Services usually
hold database data and provide the output in JSON format to the android app. The Context
for the respective screen helps to get hold of database data and the shared data across screens

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.

Types of Context in Android


There are mainly two types of context that are available in Android.
1. Application Context
2. Activity Context

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:

This Context is tied to the Lifecycle of an Application. Mainly it is an instance that


is a singleton and can be accessed via getApplicationContext(). Some use cases of
Application Context are:
 If it is necessary to create a singleton object
 During the necessity of a library in an activity

• 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;

public class GlobalExampleClass extends Application {

private String globalName;

private String globalEmail;

public String getName() {

return globalName;

} public void setName(String aName) {

globalName = aName;

public String getEmail() {

return globalEmail;

public void setEmail(String aEmail) {

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

final String globalName = globalExampleVariable.getName();


final String globalEmail = globalExampleVariable.getEmail();
.......
}

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.

List of functionalities of Application Context:


 Load Resource Values
 Start a Service
 Bind to a Service
 Send a Broadcast
 Register BroadcastReceiver

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().

Some use cases of Activity Context are:


 The user is creating an object whose lifecycle is attached to an activity.
 Whenever inside an activity for UI related kind of operations like toast, dialogue,
etc.,

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);
}

List of Functionalities of Activity Context:


 Load Resource Values
 Layout Inflation
 Start an Activity
 Show a Dialog
 Start a Service
 Bind to a Service
 Send a Broadcast
 Register BroadcastReceiver

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:

public <YourHandler>(Context ctx) {


// if the context is instanceof ContextWrapper
while (ctx instanceof ContextWrapper) {
// use getBaseContext()
final Context baseContext = ((ContextWrapper)context).getBaseContext();
if (baseContext == null) {
break;
}
// And then we can assign to context and reuse that
ctx = baseContext;
}
}

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:

1. Sending the User to Another App


2. Getting a Result from an Activity
3. Allowing Other Apps to Start Your Activity

Some Important Method of Intent and their Description:

Prof.Rahul Khandarkar
Android Programming

Types of Android Intents


There are two types of intents in android
1. Implicit
2. Explicit

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.

For Example: In the below images, 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.

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

Returning results from activities


Starting another activity doesn't have to be one-way. You can also start another activity
and receive a result back. To receive a result, call startActivityForResult() (instead
of startActivity()).
For example, your app can start a camera app and receive the captured photo as a
result. Or, you might start the People app in order for the user to select a contact and you'll
receive the contact details as a result.
Of course, the activity that responds must be designed to return a result. When it does,
it sends the result as another Intent object. Your activity receives it in
the onActivityResult() callback.

Start the Activity:

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:

static final int PICK_CONTACT_REQUEST = 1; // The request code


...
private void pickContact() {
Intent pickContactIntent = new Intent(Intent.ACTION_PICK, new
Uri("content://contacts"));
pickContactIntent.setType(Phone.CONTENT_TYPE); // Show user only contacts
w/ phone numbers
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}

Prof.Rahul Khandarkar
Android Programming

Receive the Result:


When the user is done with the subsequent activity and returns, the system calls your
activity's onActivityResult() method. This method includes three arguments:
The request code you passed to startActivityForResult().
A result code specified by the second activity. This is either RESULT_OK if the
operation was successful or RESULT_CANCELED if the user backed out or the operation
failed for some reason.
An Intent that carries the result data.
For example, here's how you can handle the result for the "pick a contact" intent:

@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.

// Do something with the contact here (bigger example below)


}
}
}

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>

Most of the intent filter are describe by its


1. <action>,
2. <category> and
3. <data>

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:

 CATEGORY_BROWSABLE: The target activity allows itself to be started by a web


browser to display data referenced by a link.

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

Intent Filter in Manifest File: -


Following is the code snippet of defining an activity with Intent Filter (<intent-filter>)
in the Android Manifest file (AndroidManifest.xml) like as shown below.

<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.

Multiple Intent Filters in Manifest File:


In case if we want to handle multiple Intents with combinations of action, category,
and data, we need to create multiple intent filters.
Following is the code snippet of defining multiple Intent filters in the android manifest file
to handle multiple Intents.
<activity android:name=".MainActivity">
<!-- This activity is the main entry, should appear in app launcher -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
<activity android:name=".ResultActivity">
<!-- This activity handles "SEND" actions with text data -->
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>
Prof.Rahul Khandarkar
Android Programming

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.

Android Intent Filters Example:


Following is the complete example of using Intent Filters in android applications. Here we
will configure and send an email using Intent Filters in the android application.

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

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/sendMail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="230dp"
android:text="Send Mail" />
</LinearLayout>

Now open our main activity


file MainActivity.java from \src\main\java\com.tutlane.intents path and write the code like as
shown below.

Prof. Manasi Talele 22


Android Programming

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”

Prof. Manasi Talele 23


Android Programming
putExtra - we use this putExtra() method to add extra information to our Intent. Here we
add the following things.

EXTRA_EMAIL – It’s an array of email addresses


EXTRA_SUBJECT – The subject of the email that we want to send
EXTRA_TEXT – The body of the email
Now open android manifest file (AndroidManifest.xml) and write the code like as shown
below

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutlane.intentfilters">

<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.

Prof. Manasi Talele 24


Android Programming
action - we use this property to define that the activity can perform SEND action.

category - we included the DEFAULT category for this activity to be able to receive implicit
intents.

data - the type of data the activity can send.

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.

Application of implicit intents:

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:

Intent intent = new Intent(Intent.ACTION_VIEW,


Uri.parse("https://www.example.com"));
startActivity(intent);

 This implicit intent opens a web page using the default web browser.

2. Dialing a Phone Number:

Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));


startActivity(intent);

 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.

Intent browserIntent = new Intent(Intent.ACTION_VIEW,


Uri.parse("https://www.example.com"));
startActivity(browserIntent);

Prof. Manasi Talele 26


Android Programming
 System to open the appropriate application, such as a web browser.

4. Opening Maps for Navigation:

Uri locationUri = Uri.parse("geo:37.7749,-122.4194?q=San+Francisco");


Intent mapIntent = new Intent(Intent.ACTION_VIEW, locationUri);
startActivity(mapIntent);

 Implicit intents can be employed to open a map application for navigation to a specific
location using geo-coordinates.

5. Sending Emails or Text Messages:

Intent emailIntent = new Intent(Intent.ACTION_SENDTO,


Uri.parse("mailto:[email protected]"));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body of the email");
startActivity(emailIntent);

 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:

Intent shareIntent = new Intent(Intent.ACTION_SEND);


shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "Shared content goes here");
startActivity(Intent.createChooser(shareIntent, "Share using"));

 Implicit intents facilitate content sharing between applications. By creating an


Intent.ACTION_SEND intent, you can share text, images, or other content with other
apps on the device.

Prof. Manasi Talele 27


Android Programming

7. Opening Camera or Gallery:

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);


startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);

 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.

8. Playing Media Files:

Uri videoUri = Uri.parse("android.resource://com.example.app/raw/sample_video");


Intent videoIntent = new Intent(Intent.ACTION_VIEW, videoUri);
startActivity(videoIntent);

 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 life cycle:


• Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class.
The android Activity is the subclass of ContextThemeWrapper class.
• An activity is the single screen in android. It is like window or frame of Java.
• By the help of activity, you can place all your UI components or widgets in a single
screen.
• The 7-lifecycle method of Activity describes how activity will behave at different states.

Prof. Manasi Talele 28


Android Programming

Android Activity Lifecycle methods:

Prof. Manasi Talele 29


Android Programming

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.

Prof. Manasi Talele 30


Android Programming

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”

What Happens on Back Press?


• If the user presses Back repeatedly, each activity in the stack is popped off to show the one
before it, until the user returns to the Home screen
• The task is no longer active after all actions have been removed from the stack.
• A task is a logical unit that may be sent to the “background” when users start a new task or
press the Home button to return to the Home screen.
• All operations in the task are paused while it is in the background, but the task’s back stack
remains intact—the task has just lost focus while another task is being performed.

Prof. Manasi Talele 31


Android Programming

• 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

Prof. Manasi Talele 32


Android Programming

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.

Application’s priority and its process:


• In general, a particular android device has limited storage capacity and processing speed, but
since there are so many applications running on the user device, it becomes challenging for
the android operating system to manage the resource properly so that all the processes should
get the resource.
• So android operating system pushes the least used application in a cache called as LRU (Least
Recently Used) Cache, if the application has not been used for the very long time, it will be
pushed to the queue of the LRU and will be present at the front of the queue.
• If the application comes into use in the near time, it will be near to the back of the queue, &
if the application is most recently used it will be present at the back of the queue.
• For example, if the user has not used Facebook for a very long time, then the Facebook
application will be present at the front of the queue and if let’s suppose the user has used
WhatsApp recently, then it will be present at the back of the LRU Cache queue.
• The LRU Cache Queue
• To determine which process should be killed to proper memory and battery management, the
Android operating system maintains a hierarchy in which all the processes are placed in order
of their priority.
• The less priority is the process which can be killed first when the system wants to free up
some resource

Prof. Manasi Talele 33


Android Programming
• Android uses some set of rules and regulations to decide the priority of the processes based
on the running state of the applications
• There are four process states that a process may have at any time in android applications.
• The priority of these processes decreases from top to down in order in which they are listed.

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.

Prof. Manasi Talele 34


Android Programming
• These processes would be killed only when keeping them alive make it impossible for the
foreground process to continue their execution.
• Example: When some application needs permission like camera access, storage access, etc a
prompt or dialog box will appear and ask for the required permission. So at this time, the
process corresponding to the activity of the app which is running previously will go in the
visible state.

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.

Prof. Manasi Talele 35


Android Programming

States fragments and its life cycle:


• In Android, the fragment is the part of Activity which represents a portion of User Interface
(UI) on the screen.
• It is the modular section of the android activity that is very helpful in creating UI designs that
are flexible in nature and auto-adjustable based on the device screen size.
• The UI flexibility on all devices improves the user experience and adaptability of the
application.
• Fragments can exist only inside an activity as its lifecycle is dependent on the lifecycle of
host activity.
• For example, if the host activity is paused, then all the methods and operations of the fragment
related to that activity will stop functioning, thus fragment is also termed as sub-activity.
• Fragments can be added, removed, or replaced dynamically i.e., while activity is running.
• tag is used to insert the fragment in an android activity layout.
• By dividing the activity’s layout multiple fragments can be added in it.

Types of Android Fragments:


1. Single Fragment: Display only one single view on the device screen. This type of fragment
is mostly used for mobile phones.
2. List Fragment: This Fragment is used to display a list-view from which the user can select
the desired sub-activity. The menu drawer of apps like Gmail is the best example of this kind
of fragment.
Prof. Manasi Talele 36
Android Programming
3. Fragment Transaction: This kind of fragments supports the transition from one fragment
to another at run time. Users can switch between multiple fragments like switching tabs.

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.

Prof. Manasi Talele 37


Android Programming

Methods of the Android Fragment:


onAttach() :
The very first method to be called when the fragment has been associated with the
activity. This method executes only once during the lifetime of a fragment.
onCreate() :
This method initializes the fragment by adding all the required attributes and
components.
onCreateView():
• System calls this method to create the user interface of the fragment.
• The root of the fragment’s layout is returned as the View component by this method to
draw the UI.
onViewCreated():
• It indicates that the activity has been created in which the fragment exists.
Prof. Manasi Talele 38
Android Programming
• View hierarchy of the fragment also instantiated before this function call.
onStart():
• The system invokes this method to make the fragment visible on the user’s device.
onResume():
This method is called to make the visible fragment interactive.
onPause():
• It indicates that the user is leaving the fragment.
• System calls this method to commit the changes made to the fragment.
onStop():
• Method to terminate the functioning and visibility of fragment from the user’s screen.
onDestroyView() :
• System calls this method to clean up all kinds of resources as well as view hierarchy
associated with the fragment.
onDestroy() :
• It is called to perform the final clean-up of fragment’s state and its lifecycle.
onDetach():
• The system executes this method to disassociate the fragment from its host activity
• Fragments are always embedded in Activities
• They are added to the layout of activity in which they reside. Multiple fragments can
be added to one activity.
• This task can be carried out in 2 ways:
1. Statically:
 Explicitly mention the fragment in the XML file of the activity.
 This type of fragment cannot be replaced during the run time.

2. Dynamically:
 FragmentManager is used to embed fragments with activities that enable the
addition, deletion, or replacement of fragments at run time

Prof. Manasi Talele 39

You might also like