Activities and Intents

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 57

Understanding the Components of a

Screen
• Application components are the essential building blocks of an Android application
• These components are loosely coupled by the application manifest file
AndroidManifest.xml that describes each component of the application and how they
interact
Activities
• An activity represents a single screen with a user interface,in-short Activity performs actions on the screen
• For example, an email application might have one activity that shows a list of new emails, another activity
to compose an email, and another activity for reading emails.
• If an application has more than one activity, then one of them should be marked as the activity that is
presented when the application is launched.

public class MainActivity extends Activity {

Services
• A service is a component that runs in the background to perform long-running operations
• For example, a service might play music in the background while the user is in a different application, or it
might fetch data over the network without blocking user interaction with an activity.

public class MyService extends Service {

}
Broadcast Receivers
• Broadcast Receivers simply respond to broadcast messages from other applications or from the system
• For example, applications can also initiate broadcasts to let other applications know that some data has been
downloaded to the device and is available for them to use, so this is a broadcast receiver who will intercept this
communication and will initiate appropriate action
• A broadcast receiver is implemented as a subclass of BroadcastReceiver class and each message is broadcast as
an Intent object
public class MyReceiver extends BroadcastReceiver {
public void onReceive(context,intent){}
}

Content Providers
• A content provider component supplies data from one application to others on request. Such requests are
handled by the methods of the ContentResolver class
• The data may be stored in the file system, the database or somewhere else entirely
• A content provider is implemented as a subclass of ContentProvider class and must implement a standard set of
APIs that enable other applications to perform transactions

public class MyContentProvider extends ContentProvider {


public void onCreate(){}
}
Additional Components
Activity
Lifecycle
•Good implementation of the lifecycle callbacks
avoid the following:
• Crashing if the user receives a phone call or
switches to another app while using your
app.
• Consuming valuable system resources when
the user is not actively using it.
• Losing the user's progress if they leave your
app and return to it at a later time.
• Crashing or losing the user's progress when
the screen rotates between landscape and
portrait orientation.
Activity Lifecycle
Method Description
onCreate(Bundle called when activity is first created.
savedInstanceState)
onStart() called when activity is becoming visible to the user.
The activity is now in the foreground but may not have the focus.

onResume() called when activity will start interacting with the user
The activity is in the foreground and has focus.

onPause() called when activity is no longer in focus


This method is typically used to release resources and save persistent data.

onStop() called when activity is no longer visible to the user.


Resources that are not needed when the activity is not visible can be released
here
Clean up resources, unregister listeners, or perform other cleanup activities.
onRestart() called after your activity is stopped, prior to start.
Called when the activity is stopped and then starts again.

onDestroy() called before the activity is destroyed.


LIKELIHOOD OF FINAL ACTIVITY
PROCESS STATE
BEING KILLED STATE

Lowest Foreground (having or Resumed


about to get focus)

Low Visible (no focus) Started/Paused

Higher Background (invisible) Stopped

Highest Empty Destroyed


Difference between Activity and AppCompatActivity

• AppCompatActivity provides native ActionBar support that is


consistent across the application. Also, it provides backward
compatibility for other material design components till SDK version
7(ActionBar was natively available since SDK 11). Extending an
Activity doesn’t provide any of these.
• Note: Since SDK 21 every activity by default, extends
AppCompatActivity.
How does the activity respond when the
user rotates the screen?
• When the screen is rotated, the current instance of the activity is
destroyed a new instance of the Activity is created in the new
orientation
• The onRestart() method is invoked first when a screen is rotated
• The other lifecycle methods get invoked in the similar flow as they
were when the activity was first created.
How to prevent data from reloading & resetting when the screen is rotated?
The most basic approach is to add an element attribute tag android:configChanges inside the activity tag in
the AndroidManifest.xml as shown below.
<activity android:name=".MainActivity"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

In general, the configChanges for any activity are defined as

android:configChanges="orientation|screenSize|keyboardHidden"

The keyboardHidden configuration is to prevent the keyboard from resetting if it’s pulled out
Where do onSaveInstanceState() and onRestoreInstanceState()
come in the activity lifecycle? How is the data saved and restored
from these methods?
• In general the onSaveInstanceState() is invoked after onPause() and
before the onStop()
• But the API documentation explicitly states that the onSaveInstanceState(
) method will be called before onStop() but makes no guarantees it will
be called before or after onPause()
• The onRestoreInstanceState() is called after onStart() is invoked
• The onRestoreInstanceState() method is invoked only when the activity
was killed before. If the activity is NOT killed the onSaveInstanceState()
is NOT called
How to keep the screen orientation fixed? Also implement a
mechanism so that the screen is always on for a particular activity

The screen orientation can be fixed by adding the attribute


android:screenOrientation="portrait" or
android:screenOrientation="landscape" in the activity tag.

To keep the screen always on for a particular screen add the


android:keepScreenOn="true" in the root tag of the activity layout.
Which method gets invoked when the user presses back button on the screen?
The onBackPressed() method of the Activity is invoked. Unless overridden it removes the
current activity from the stack and goes to the previous activity

How do you disable onBackPressed()?

The onBackPressed() method is defined as shown below:


@Override
public void onBackPressed() {
super.onBackPressed();
}

To disable the back button and preventing it from destroying the current activity and going back we
have to remove the line super.onBackPressed();
Intent
• This process of taking users from one application to another is achieved by
passing the Intent to the system
• Used for navigating among various activities within the same application, and
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
• It is mainly used to
• Start the service
• Launch an activity
• Display a web page
• Display a list of contacts
• Broadcast a message
• Dial a phone call etc.
Important Method of Intent

Methods Description
Context.startActivity() This is to launch a new activity or get an existing activity to be action.

Context.startService() This is to start a new service or deliver instructions for an existing service.

Context.sendBroadcast() This is to deliver the message to broadcast receivers.


Implicit Intent
• Implicit Intents do not directly specify the Android components
which should be called, it only specifies action to be performed
• A Uri can be used with the implicit intent to specify the data type.

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse(“lms.vit.ac.in"));
startActivity(intent);
Dialing a number

Sending an email to a group of email-addresses

Intent email= new Intent(Intent.ACTION_SENDTO);


email.setData(Uri.parse("mailto:"));
email.putExtra(Intent.EXTRA_SUBJECT, "Subject");
email.putExtra(Intent.EXTRA_TEXT, "My Email message");
email.putExtra(Intent.EXTRA_EMAIL,new String[]{"aaa@gmail.com","bb@gmail.com"});
email.putExtra(Intent.EXTRA_CC,new String[]{"aaaa@gmail.com","bbb@gmail.com"});
startActivity(email);
Explicit Intent
Explicit Intent specifies the component. In such case, intent
provides the external class to be invoked

Intent i = new Intent(getApplicationContext(), ActivityTwo.class);


startActivity(i);
Building Blocks of an Intent
• Component name : Represents the component's name (or component
category) to start. Optional, used while declaring an explicit intent and a
service.

• Action: represents the action to be taken/performed.


• ACTION_VIEW is used to show some information to the user
• ACTION_SEND is used to share some data using a 3rd party application.
Building Blocks of an Intent
• Data: Represents the type of data to be sent. For data URI, setData() is
called and for the MIME type, setType() is called
intent.setData(Uri.parse("http://www.google.com"));
To get data
Uri locationUri = intent.getData();

• Flags: Instruct the Android system on how to launch activity and treat it
after it is launched using setFlags()
• FLAG_ACTIVITY_CLEAR_TASK finished all the old activities (associated
with the activity) before starting the activity via the startActivity()
method.
Building Blocks of an Intent
Extras: The key-value pairs that contain extra information to perform the
requested action

putExtra(String name, type value)


intent.putExtra("level", 406);

String[] foodList = {"Rice", "Beans", "Fruit"};


intent.putExtra("food", foodList);

putExtras(bundle);
Building Blocks of an Intent
getData();
Uri locationUri = intent.getData();
int getIntExtra (String name, int defaultValue)
int level = intent.getIntExtra("level", 0);
Bundle bundle = intent.getExtras();
Get all the data at once as a bundle.
Building Blocks of an Intent
Sending and retrieving data
• In the first (sending) activity:
• Create the Intent object
• Put data or extras into that intent
• Start the new activity with startActivity()
• In the second (receiving) activity,:
• Get the intent object the activity was started with
• Retrieve the data or extras from the Intent object
Sending Activity
Intent intent = new Intent(getApplicationContext(), Second.class);
int a[]={1,2,3,4,5};
intent.putExtra("Values",a);
intent.putExtra("int",5);
intent.putExtra("float",5.0f);
startActivity (intent);

Receiving Activity
Intent i=getIntent();
int a[]=i.getIntArrayExtra("Values");
String result=""+a[0];
result+=i.getIntExtra("int",0); //Separate methods are available for each type of passed value
result+=i.getFloatExtra("float",0.0f);
Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
Sharing text data with other application

Sharing an image file with other application


Difference between Intent and Bundle in
Passing Value
• Bundle can operate on objects, but Intent can’t
• Bundle has more interfaces than Intent and is more flexible to use, but
using Bundle also needs Intent to complete data transfer.
• In a word, Bundle aims to store data, while Intent aims to transfer
value
Intent mode
Suppose you need to pass data from page A to B and then to C.
On page A:
Intent intent=new Intent(MainActivity.this,BActivity.class);
Intent. putExtra ("String", "Value in MainActivity"); intent.putExtra("int",11);
startActivity(intent);
On page B:
You need to receive data in page B first
Intent intent = getIntent();
string = intent.getStringExtra("String"); key = intent.getIntExtra("int",0);
Then send data to C page.
Intent intent=new Intent(BActivity.this,CActivity.class);
intent.putExtra("String1",string); intent.putExtra("int1",key); intent.putExtra("boolean",true);
startActivity(intent);
As you can see, the inconvenience of using B pages is that you need to take data out one by one and then transfer it to C
pages one by one.
Bundle mode

On page A:
Intent intent = new Intent(MainActivity.this, BActivity.class);
Bundle bundle = new Bundle();
bundle. putString ("String", "Value in MainActivity"); bundle.putInt("int",11);
intent.putExtra("bundle",bundle);
startActivity(intent);
Receive data on page B:
Intent intent = getIntent();
bundle=intent.getBundleExtra("bundle");
Then send data in page B:
Intent intent=new Intent(BActivity.this,CActivity.class);
// Additional values that can be passed to C Activity
bundle.putBoolean("boolean",true);
intent.putExtra("bundle1",bundle);
startActivity(intent);
What is a service?
• A service is a component in android that’s used for performing tasks in the background
such as playing Music, location updating etc.
• Unlike activities, a service does not have a UI. Also, a service can keep running in the
background even if the activity is destroyed

How to start/stop a service?

A service is started from an activity by executing the following code snippet.

startService(new Intent(this, MyService.class));

Though just executing the above code won’t start a service. We need to register the service
first in the AndroidManifest.xml file as shown below.

<service android:name="MyService"/>

To stop a service we execute stopService(). To stop the service from itself we call stopSelf().
Foreground services are visible to the users. The
users can interact with them at ease and track what’s
happening. These services continue to run even when
users are using other applications.
Example : Music Player and Downloading.

Background Services run in the background, such


that the user can’t see or access them
Example: Syncing and Storing data

Bound service runs as long as some other application


component is bound to it. Many components can
bind to one service at a time, but once they all
unbind, the service will destroy.
• The system calls onStartCommand() method whenever a component, say an activity requests ‘start’ to
a service, using startService(). Once we use this method it’s our duty to stop the service using
stopService() or stopSelf()

• onBind() is invoked when a component wants to bind with the service by calling bindService(). In this,
we must provide an interface for clients to communicate with the service. For interprocess
communication, we use the IBinder object.

• The system invokes onUnbind() when all the clients disconnect from the interface published by the
service.

• The system calls onRebind() method when new clients connect to the service. The system calls it after
the onBind() method.

• onCreate() is the first callback method that the system calls when a new component starts the service.
We need this method for a one-time set-up.

• onDestroy() method is the final clean up call for the system. The system invokes it just before the
service destroys. It cleans up resources like threads, receivers, registered listeners, etc.
Define and differentiate between Bound Services and Unbound/Started Services

Bound Services: An Android component may bind itself to a Service using


bindservice(). A bound service would run as long as the other application components
are bound to it. As soon as the components call unbindService(), the service destroys
itself.

Unbound Services: A service is started when a component (like activity) calls


startService() method and it runs in the background indefinitely even if the original
component is destroyed.
Broadcast Receiver
• Android Broadcast Receiver is an Android component that is used to broadcast the
messages to the system or other applications
• The broadcast message is referred to as an Event or Intent
• Broadcast receivers, unlike Activities, have no user interface
• It’s working is similar to that of a publish-subscribe design pattern
• It’s used for Asynchronous Inter-Process communication
System-generated Intents

android.intent.action.BATTERY_CHANGED – This keeps track of the battery’s charging state, percentage,


and other information about the battery.
android.intent.action.BATTERY_LOW – It indicates the low battery condition.
android.intent.action.POWER_CONNECTED
android.intent.action.POWER_DISCONNECTED
android.intent.action.BOOT_COMPLETED – This broadcast is shown only once when the device boots for
the first time.
android.intent.action.CALL – This intent is to perform a call to some specific person, according to data.
android.intent.action.DATE_CHANGED
android.intent.action.REBOOT
android.intent.action.CONNECTIVITY_CHANGE – This shows the network connectivity of the device has
changed.
android.intent.action.BUG_REPORT – This reports the bugs if there is any.
android.intent.action.CALL_BUTTON – The user pressed the call button to make a call, which takes them
to an appropriate user interface.
Types of broadcast receivers

Ordered Broadcasts
• Ordered Broadcasts are synchronous broadcasts, and are done in proper order and the order is decided by the
android:priority attribute
• The broadcast with the highest priority would execute first and broadcasts with the same priority would not follow
any order.
• In this, one broadcast is delivered only to one receiver at a time. When a receiver receives a broadcast it’s up to the
receiver to pass or abort the broadcast. If a receiver wants, it passes the broadcast to the next receiver else the
broadcast doesn’t reach the next receiver.

Normal Broadcasts
• Normal broadcasts are asynchronous and unordered
• These receivers run unorderly or all at a time, sometimes. That’s why they are efficient, but lack full utilization of the
results
• These broadcasts are sent using Context:sendBroadcast.
• In normal broadcast, it’s possible that the system sends only one broadcast at a time in order to avoid overhead. It
can also abort the broadcast, but those excluding APIs.
• Notification that we receive from the applications can also be muted.
Implementation of Broadcast Receivers
Context-registered
This is also known as the dynamically registering method and the registration is done using
Context.registerReceiver()

IntentFilter filter = new IntentFilter();


intentFilter.addAction(getPackageName()+"android.net.conn.CONNECTIVITY_CHANGE");
MyReceiver myReceiver = new MyReceiver();
registerReceiver(myReceiver, filter);

Manifest-registered
This is also known as the statically registering method
<receiver android:name="DataFlairReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Need Of Fragments In Android
• Before the introduction of Fragment’s we can only show a single Activity on
the screen at one given point of time
• We were not able to divide the screen and control different parts
separately
• With the help of Fragment’s we can divide the screens in different parts
and controls different parts separately.
• By using Fragments we can comprise multiple Fragments in a single Activity
• Fragments have their own events, layouts and complete life cycle
• It provide flexibility and also removed the limitation of single Activity on
the screen at a time.
Fragments
• Fragments cannot live on their own--they must be hosted by an activity or
another fragment
• Fragments introduce modularity and reusability into your activity’s UI by
allowing you to divide the UI into discrete chunks
• Dividing your UI into fragments makes it easier to modify your activity's
appearance at runtime
• While your activity is in the STARTED lifecycle state or higher, fragments can
be added, replaced, or removed
• You can keep a record of these changes in a back stack that is managed by
the activity, allowing the changes to be reversed.
• You can use multiple instances of the same fragment class within the same
activity, in multiple activities, or even as a child of another fragment
• Fragments were added in Honeycomb version of Android i.e API version 11
Fragment Life Cycle
Fragment Life Cycle
• 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() Calls when creating the fragment. Initialize essential components of the fragment that you want to retain when the fragment is

paused or stopped, then resumed.

• onCreateView() Calls 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() Called after the onCreateView() method when the host activity is created. At this point, view can be accessed with the

findViewById() method.

• onStart() Called once the fragment gets visible. onResume() Calls when Fragment becomes active.

• onPause() 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 method
various fragment lifecycle events:

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof Activity){
this.listener = (FragmentActivity) context;
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayList<Thing> things = new ArrayList<Thing>();
adapter = new ThingsAdapter(getActivity(), things);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_some, parent, false);
}
various fragment lifecycle events:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView lv = (ListView) view.findViewById(R.id.lvSome);
lv.setAdapter(adapter);
}
@Override
public void onDetach() {
super.onDetach();
this.listener = null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Basic Fragment Code In XML
<fragment
android:id="@+id/fragments"
android:layout_width="match_parent"
android:layout_height="match_parent" />

Create A Fragment Class In Android Studio

public class FirstFragment extends Fragment {


@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
How to use Fragments?
This involves number of simple steps to create Fragments.
1. Decide how many fragments you want to use in an activity
2. Based on number of fragments, create classes which will extend
the Fragment class. The Fragment class has above mentioned
callback functions. You can override any of the functions based on
your requirements.
3. Corresponding to each fragment, you will need to create layout
files in XML file. These files will have layout for the defined
fragments.
4. Finally modify activity file to define the actual logic of replacing
fragments based on your requirement
Defining a Fragment
A fragment, like an activity, has an XML layout file and a Java class that represents the Fragment controller

The Java controller for a fragment looks like

import androidx.fragment.app.Fragment;
public class FooFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
// Defines the xml file for the fragment
return inflater.inflate(R.layout.fragment_foo, parent, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
}
Embedding a Fragment in an Activity
• There are two ways to add a fragment to an activity
• Dynamically using Java
• Statically using XML.
• Before embedding a "support" fragment in an Activity make sure the Activity extends
FragmentActivity or AppCompatActivity which adds support for the fragment manager to all
Android versions

Statically
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent“ android:layout_height="match_parent"
android:orientation="vertical" >
<fragment Class Name defining
android:name="com.example.android.FooFragment" Fragment
android:id="@+id/fooFragment“
android:layout_width="match_parent" android:layout_height="match_parent" />
</LinearLayout>
Embedding a Fragment in an Activity
Dynamically
The FragmentManager class and the FragmentTransaction class allow you to add, remove and replace
fragments in the layout of your activity at runtime.

// Begin the transaction


FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

// Replace the contents of the container with the new fragment


ft.replace(R.id.your_placeholder, new FragmentClass());
(OR)
ft.add(R.id.your_placeholder, new FragmentClass());

// Complete the changes added above


ft.commit();
Finding Fragment By ID

If the fragment was statically embedded in the XML within an activity and given an
android:id such as fragmentDemo then we can lookup this fragment by id by calling
findFragmentById on the FragmentManager

public class MainActivity extends AppCompatActivity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
}
}
}
Communicating with Fragments

• Fragments should generally only communicate with their direct parent activity allowing
the activity to manage the inputs and outputs of data from that fragment coordinating
with other fragments or activities
• Think of the Activity as the controller managing all interaction with each of the
fragments contained within.
• A few exceptions to this are dialog fragments presented from within another fragment
or nested child fragments
• Both of these cases are situations where a fragment has nested child fragments and
that are therefore allowed to communicate upward to their parent (which is a
fragment)
In other words, communication should generally follow these principles

• Activities can initialize fragments with data during construction


• Activities can pass data to fragments using methods on the fragment
instance
• Fragments can communicate up to their parent activity using an interface
and listeners
• Fragments should pass data to other fragments only routed through their
parent activity
• Fragments can pass data to and from dialog fragments
• Fragments can contain nested child fragments
Fragment Methods (Send data from host to Fragment activity)

If an activity needs to make a fragment perform an action after initialization, the easiest way is by having the activity
invoke a method on the fragment instance. In the fragment, add a method

public class DemoFragment extends Fragment {


public void doSomething(String param) {
// do something in fragment
}
}
and then in the activity, get access to the fragment using the fragment manager and call the method:

public class MainActivity extends AppCompatActivity {


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentById(R.id.fragmentDemo);
fragmentDemo.doSomething("some param");
}
}
Fragment to Host
Activity
• Define an interface in Fragment class with a method and declare a reference variable of reference type
public interface onSomeEventListener {
public void someEvent(String s);
}
onSomeEventListener someEventListener;

public void onAttach(@NonNull Context context) {


super.onAttach(context);
c= (onSomeEventListener) context;
}
• Implement onSomeEventListener interface in host activity class and implement someEvent() method
and write necessary code
@Override
public void someEvent(String s) {
Fragment frag1 = getSupportFragmentManager().findFragmentById(R.id.fragment1);
((TextView)frag1.getView().findViewById(R.id.textView)).setText("Text from Fragment 2:" + s);
}
Activity, AppCompatActivity, FragmentActivity and
ActionBarActivity. How are they related?

• Activity is the base class. FragmentActivity extends Activity.


AppCompatActivity extends FragmentActivity. ActionBarActivity
extends AppCompatActivity.
• FragmentActivity is used for fragments.
• Since the build version 22.1.0 of the support library, ActionBarActivity
is deprecated. It was the base class of appcompat-v7.
• At present, AppCompatActivity is the base class of the support library.
It has come up with many new features like ToolBar, tinted widgets,
material design color pallets etc.
References
• https://data-flair.training/blogs/android-tutorial/
• https://data-flair.training/blogs/android-projects-with-source-code/
• https://www.journaldev.com/10929/android-interview-questions-and
-answers
• https://abhiandroid.com/ui/fragment
• https://guides.codepath.com/android/Creating-and-Using-Fragments

You might also like