UNIT II - ActivityLifeCycle - UnderstandingActivities

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

UNIT II

BUILDING BLOCKS OF ANDROID APPLICATION

(Components of Android Application)


 Application components are the essential building blocks of an Android application.
 These components are listed in a manifest file called AndroidManifest.xml that describes each
component of the application and how they interact.
 There are following four main components that can be used within an Android application –
 Activities
 Services
 Broadcast Receivers
 Content Providers

Sr.No Components & Description

Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.
Services
2
They handle background processing associated with an application.
Broadcast Receivers
3
They handle communication between Android OS and applications.
Content Providers
4
They handle data and database management issues.

1. Activities
 An activity represents a single screen with a user interface. Activity performs actions on the screen.
 It is specific combination of XML files and JAVA files. It is basically a container that contains the
design as well as coding stuff.
 XML files provide the design of the screen and JAVA files deal with all coding stuff.

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.

 An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity {


}
2. Services
 A service is a component that runs in the background to perform long-running operations.

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.

 A service is implemented as a subclass of Service class as follows –

public class MyService extends Service {


}

3.Broadcast Receivers

 Broadcast Receivers simply respond to broadcast messages from other applications or from the system.

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


broadcaster as an Intent object.

public class MyReceiver extends BroadcastReceiver {


public void onReceive(context,intent){}
}

4.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(){}
}

ANDROIDMANIFEST.XML FILE
 Every app project must have an AndroidManifest.xml file, with precisely that name, at the root of
the project source set.
 The manifest file describes essential information about your app to the Android build tools, the Android
operating system, and Google Play.
 Among many other things, the manifest file is required to declare the following:
1. The components of the app, including all activities, services, broadcast receivers, and
content providers.
 Each component must define basic properties, such as the name of its Kotlin or
Java class.
 It can also declare capabilities, such as which device configurations it can handle, and
intent filters that describe how the component can be started. Read more about app
components in a following section.

2. The permissions that the app needs in order to access protected parts of the system or
other apps.
 It also declares any permissions that other apps must have if they want to
access content from this app.

For example, an app that needs to send SMS messages must have the following line in
the manifest:
<manifest ... >
<uses-permission android:name="android.permission.SEND_SMS"/>
...
</manifest>

3. The hardware and software features the app requires, which affects which devices can
install the app from Google Play.

Manifest elements
The following table provides some of the elements of Manifest (AndroidManifest.xml file).

Attribute

<action> Adds an action to an intent filter.


<activity> Declares an activity component.
<activity-alias> Declares an alias for an activity.
<application> Declares the application.
<category> Adds a category name to an intent filter.
<compatible- Specifies each screen configuration the application is compatible with.
screens>
<data> Adds a data specification to an intent filter.
<grant-uri- Specifies the subsets of app data that the parent content provider has permission to access.
permission>
<instrumentation> Declares an Instrumentation class that lets you monitor an application's interaction with the
system.
<intent-filter> Specifies the types of intents that an activity, service, or broadcast receiver can respond to.
<manifest> The root element of the AndroidManifest.xml file.
<meta-data> A name-value pair for an item of additional, arbitrary data that can be supplied to the parent
component.
<path-permission> Defines the path and required permissions for a specific subset of data within a content
provider.
<permission> Declares a security permission that can be used to limit access to specific components or
features of this or other applications.
<permission-group> Declares a name for a logical grouping of related permissions.
<permission-tree> Declares the base name for a tree of permissions.
<provider> Declares a content provider component.
<queries> Declares the set of other apps that your app intends to access. Learn more in the guide
about package visibility filtering.
<receiver> Declares a broadcast receiver component.
<service> Declares a service component.
<supports-gl- Declares a single GL texture compression format that the app supports.
texture>

Example Manifest File


<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0">

<!-- Beware that these values are overridden by the build.gradle file -->
<uses-sdk android:minSdkVersion="15" android:targetSdkVersion="26" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!-- This name is resolved to com.example.myapp.MainActivity


based on the namespace property in the build.gradle file -->
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<activity
android:name=".DisplayMessageActivity"
android:parentActivityName=".MainActivity" />
</application>
</manifest>
UNDERSTANDING ACTIVITIES
 An activity represents a single screen with a user interface. Activity performs actions on the screen.
 It is specific combination of XML files and JAVA files. It is basically a container that contains the
design as well as coding stuff.
 XML files provide the design of the screen and JAVA files deal with all coding stuff.
Activities include following details:
1) Lifecycle Of Activity
2) Linking Activities Using Intents
3) Applying Styles and Themes to an Activity
4) Hiding the Activity Title

1.Lifecycle Of Activity
An activity goes through a number of states. Activity lifecycle in Android manages the different states of
activity, such as when the activity starts or stops, etc. All of these states are managed by callback methods.

There are seven callback methods:-

onCreate():-
 Called when the activity is first created.
Example:
when we open the app it will call onCreate(), onStart(), and onResume() methods. These three methods
are initiated when you open an app.

onStart():-
 Called when the activity becomes visible to the user
 There should always be an onStart() callback after onCreate() finishes.
 In the started state, users will be able to see the activity but they are not ready for user interaction.

onResume():-
 Called when the activity starts interacting with the user
 In this, activities will be in the foreground and ready for user interaction.

onPause():-
 Called when the current activity is being paused and the previous activity is being resumed
 It is the opposite of onResume().

onStop():-
 Called when the activity is no longer visible to the user

onRestart():-
 Called when the activity has been stopped and is restarting again

onDestroy():-
 Called before the activity is destroyed by the system
 This starts when the system needs to free memory or when finish() is called.
 It is used for cleanup which is a very common activity.

By default, the activity created for you contains the onCreate() event.

2.Linking Activities Using Intents


 Intent are the objects which is used in android for passing the information among Activities in an
Application and from one app to another also.
 Intent are used for communicating between the Application components and it also provides the
connectivity between two apps.
Example:
Intent facilitate you to redirect your activity to another activity on occurrence of any event. By calling,
startActivity() to perform this task.
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
startActivity(intent);
In the above example, foreground activity is getting redirected to another activity i.e.
SecondActivity.class.
getApplicationContext() returns the context for your foreground activity.
Types of Intents:
Intent are of two types:
 Explicit Intent
 Implicit Intent

Explicit Intent:
 Explicit Intents are used to connect the application internally.
 In Explicit we use the name of component which will be affected by Intent.
Example: If we know class name then we can navigate the app from One Activity to another activity
using Intent. In the similar way we can start a service to download a file in background process.
Explicit Intent work internally within an application to perform navigation and data transfer.
Implicit Intent:
 In Implicit Intents we do need to specify the name of the component. We just specify the Action which
has to be performed and further this action is handled by the component of another application.
 The basic example of implicit Intent is to open any web page

3.Applying Styles and Themes to an Activity


 By default, an activity is themed to the default Android theme.
 There are two versions of the Material theme available to Android developers:
 Material Light
 Material Dark.
 Either of these themes can be applied from the AndroidManifest.xml.
 To apply one of the Material themes to an activity, simply modify the <Application> element in
 the AndroidManifest.xml file by changing the default android:theme attribute.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.jfdimarzio.activity101">
<application
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@android:style/Theme.Material">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Changing the default theme to @android:style/Theme.Material, applies the Material Dark theme and
gives your application a darker look.

4.Hiding the Activity Title


You can also hide the title of an activity if desired (such as when you just want to display a status update to the
user). To do so, use the requestWindowFeature() method and pass it the Window.FEATURE_NO_TITLE
constant

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Window;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
}

Displaying a Dialog Window


 A Dialog is a small window that prompts the user to make a decision or enter additional information.
 Dialogs are normally used for notifications and short messages that directly relate to the application in
progress.
Display a dialog window to get a confirmation from the user.
 Override the onCreateDialog() protected method defined in the Activity base class to display a dialog
window.
Example:
Displaying a Dialog Window Using an Activity (Dialog.zip)
1. Using Android Studio, create a new Android project and name it Dialog. When presented with
the option, name the main activity DialogActivity.
2. Add the following theme in bold to the AndroidManifest.xml file.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jfdimarzio.dialog" >
<application
android:theme="@style/AppTheme" >
<activity
android:name=".DialogActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Dialog" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

 To create a DialogFragment, create a class that extends DialogFragment and override onCreateDialog(),
as shown in the following example.
public class PurchaseConfirmationDialogFragment extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
return new AlertDialog.Builder(requireContext())
.setMessage(getString(R.string.order_confirmation))
.setPositiveButton(getString(R.string.ok), (dialog, which) -> {} )
.create();
}

public static String TAG = "PurchaseConfirmationDialog";


}

3. Compare your DialogActivity.java file


4. Show the DialogFragment
 Use the show() method to display your dialog.
 Pass a reference to a FragmentManager and a String to use as a FragmentTransaction tag.

new PurchaseConfirmationDialogFragment().show(getChildFragmentManager(),
PurchaseConfirmationDialog.TAG);

5. Press Shift+F9 to debug the application on the Android emulator. Click the button to display
the dialog.Then Dialog box is displayed on the android emulator.

Displaying a Progress Dialog


 A progress bar is a graphical control element used to visualize the progression of an extended computer
operation, such as a download, file transfer, or installation.
 Android provides a ProgressDialog class you can call when you want to display a running meter to the
user.
 ProgressDialog is easy to call from an activity.
 To create a progress dialog, you create an instance of the ProgressDialog class and call its show()
method:
progressDialog = ProgressDialog.show(this,"Please Wait", "Processing...",true);
This displays the progress dialog on the screen.

You might also like