Professional Documents
Culture Documents
Activities and Intents
Activities and Intents
Activities and Intents
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.
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.
}
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
onResume() called when activity will start interacting with the user
The activity is in the foreground and has focus.
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
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.
• 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
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
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
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.
• 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
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()
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
• 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
• 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" />
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.
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
• 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
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