1 of 31

Unit-2: Android Application Design and Resources � �

2 of 31

Activity Life Cycle

3 of 31

  • The activity instances in your app transition through different states in their lifecycle, as a user navigates through your app.
  • The Activity class provides a number of callbacks that allow the activity to know that a state has changed: that the system is creating, stopping, or resuming an activity, or destroying the process in which the activity resides.
  • Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity.

4 of 31

Activity Life Cycle

  • E.g., if you're building a streaming video player, you might;
    • Pause the video and
    • Terminate the network connection when the user switches to another app.
    • When the user returns, you can reconnect to the network and
    • Allow the user to resume the video from the same spot.

  • Life cycle methods helps you avoid:
    • 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.

5 of 31

Activity Life Cycle - Methods

onCreate()

  • You must implement this method, which fires when the system first creates the activity.
  • On activity creation, the activity enters the Created state.
  • In the onCreate() method, you perform basic application startup logic that should happen only once for the entire life of the activity.

onStart()

  • When the activity enters the Started state, the system invokes this method.
  • The onStart() call makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive.
  • E.g., this method is where the app initializes the code that maintains the UI.

6 of 31

Activity Life Cycle - Methods

onResume()

  • When the activity enters the Resumed state, it comes to the foreground, and then the system invokes the onResume() method.
  • This is the state in which the app interacts with the user.
  • The app stays in this state until something happens to take focus away from the app.
  • Such an event might be, for instance, receiving a phone call, the user’s navigating to another activity, or the device screen’s turning off.

onPause()

  • The system calls this method as the first indication that the user is leaving your activity; it indicates that the activity is no longer in the foreground.
  • Use the onPause() method to pause or adjust operations that should not continue while the Activity is in the Paused state, and that you expect to resume shortly.

7 of 31

Activity Life Cycle - Methods

onStop()

  • When your activity is no longer visible to the user, it has entered the Stopped state, and the system invokes the onStop() callback.
  • E.g.,
    • When a newly launched activity covers the entire screen.
    • The system may also call onStop() when the activity has finished running, and
    • It is about to be terminated.

onDestroy()

  • onDestroy() is called before the activity is destroyed. The system invokes this callback either because:
    • the activity is finishing (finish() being called on the activity), or
    • the system is temporarily destroying the activity due to a configuration change (such as device rotation or multi-window mode)

8 of 31

Fragments

  • In most of the applications these days, fragments are largely used.
  • As there are a lot of android devices with different resolutions, its a bit tough to handle all of those, that’s where fragments come handy. We can combine 2 or more fragments and show them in an activity.
  • A Fragment is a component that is used by an activity.
  • Even though it is used by an activity, it has its own lifecycle.
  • There are also some different fragments which you can extend: DialogFragment, ListFragment, PreferenceFragment.

9 of 31

10 of 31

Intents

  • Intent is one of the most important and most used app component of an android application.
  • Using Intents, you call to other app components or to other activity or also call other applications on your phone.
  • There are two basic kinds of intents in Android:

Explicit intents

Implicit intents

  • Explicit intents are used for communication between components of a single application.
  • Implicit intents enable interoperability between different applications.

11 of 31

EXPLICIT INTENTS

  • Explicit intents –used to launch a specific app component, such as a particular activity or service in your app.
  • Explicit intents require that specific named class to implement the desired action.
  • Class structure of an application is not known outside the application, so explicit intents are used for actions that occur within a single application.

12 of 31

EXAMPLE EXPLICIT INTENT

  • To create an explicit intent, define the component name for the Intent object—all other intent properties are optional.

Intent i = new Intent(this, SecondActivity.class); startActivity(i);

13 of 31

IMPLICIT INTENTS

  • Implicit intents do not name a specific component, but instead declare a general action to perform, which allows a component from another application to handle it.
  • For example - To show user a location on a map, use an implicit intent to request another capable application to show a specified location on a map.
  • When implicit intent called , the Android system finds the appropriate component to start by comparing the contents of the intent to the intent filters declared in the manifest file of other apps on the device.

14 of 31

EXAMPLE - IMPLICIT INTENT

String url = "http://www.vogella.com";

Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse(url));

startActivity(i);

Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.vogella.com"));

startActivity(i);

15 of 31

IMPLICIT INTENTS

  • An intent filter is an expression in an app's manifest file that specifies the type of intents that the component would like to receive.
  • By declaring an intent filter for an activity, it possible for other apps to directly start your activity with a certain kind of intent.
  • If intent filters are not declared for an activity, then it can be started only with an explicit intent.

16 of 31

IMPLICIT INTENTS

  • To ensure application security, always use an explicit intent when starting a Service and do not declare intent filters for services.
  • Using an implicit intent to start a service is a security hazard because it cannot be certain what service will respond to the intent, and the user cannot see which service starts.

17 of 31

IMPLICIT INTENTS

  • If the intent matches an intent filter, the system starts that component and delivers it the Intent object.
  • If multiple intent filters are compatible, the system displays a dialog so the user can pick which app to use.
  • The determination of Android by which components can handle a given request issued through an implicit intent is implemented through an IntentFilter.

18 of 31

IMPLICIT INTENTS

  • In order to receive implicit intents, include the CATEGORY_DEFAULT category in the intent filter.
  • Themethods startActivity() and startActivityForResult() treat all intents as if they declared the CATEGORY_DEFAULT category.
  • If you do not declare this category in your intent filter, no implicit intents will resolve to your activity.

19 of 31

INTENT FILTER

  • Intent Filter defines how your activity can be invoked by another activity.
  • An IntentFilter specifies the types of intents that an activity, service, or broadcast receiver can respond to.
  • IntentFilters are defined in the AndroidManifest.xml file.
  • For other activities to invoke your activity, specify the action and category within the <intent-filter> element in the Manifest.xml file
  • <intent-filter> element nested in the app component (such as an <activity> element).

20 of 31

INTENT FILTER

  • The system will deliver an implicit intent to your app component only if the intent can pass through one of your intent filters.
  • Each intent filter specifies the type of intents it accepts based on the intent's action, data, and category.
  • An explicit intent is always delivered to its target, regardless of any intent filters the component declares.

21 of 31

INTENT FILTER

  • Each intent filter is defined by an <intent-filter> element in the app's manifest file.
  • Inside the <intent-filter>, specify the type of intents to accept using one or more of these three elements:
  • <action>Declares the intent action accepted, in the name attribute. Value - literal string value of an action, not the class constant.
  • <category>Declares the intent category accepted, in the name attribute. Value : 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, path, etc.) and MIME type.

22 of 31

INTENT FILTER

  • An application component should declare separate filters for each unique job it can do.
  • For example, one activity in an image gallery app may have two filters: one filter to view an image, and another filter to edit an image.
  • When the activity starts, it inspects the Intent and decides how to behave based on the information in the Intent (such as to show the editor controls or not).

23 of 31

INTENT FILTER -- (MANIFEST FILE)

<activity android:name="ShareActivity"> <intent-filter> <action android:name="android.intent.action.SEND"/>

<category android:name="android.intent.category.DEFAULT"/> <data android:mimeType="text/plain"/>

</intent-filter>

</activity>

24 of 31

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.lightcone.sharingintents" android:versionCode="1" android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />

<application android:icon="@drawable/ic_launcher" android:label="@string/app_name" >

<activity android:name=".SharingIntents" android:label="@string/app_name" >

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<activity android:name=".MyLittleBrowser" android:label="@string/little_browser_name">

<intent-filter>

<action android:name="android.intent.action.VIEW" />

<category android:name="android.intent.category.DEFAULT" />

<data android:scheme="http"/>

</intent-filter>

</activity>

</application>

</manifest>

25 of 31

Example

  • Below is a simple application which has one button in one activity and when clicked to goes to other activity using intent and in the other activity, two fragments are shown.

Here we have only one button,

<?xml version="1.0" encoding="utf-8"?>�<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"�xmlns:tools="http://schemas.android.com/tools".......>�<Button�android:id="@+id/btn"�android:layout_width="wrap_content"�android:layout_height="wrap_content"�android:text="Go to another activity"�android:layout_centerVertical="true"�android:layout_centerHorizontal="true" />�</RelativeLayout>

activity_main.xml

26 of 31

  • In MainActivity so just initialize the button and set a click listener to it to call SecondActivity, this moving from one activity to another activity here is done using an Intent.

  • startActivity(new Intent(MainActivity.this, SecondActivity.class));

Package androidhunger.activityfragmentintentdemo;

import android.content.Intent;�...

public class MainActivity extends AppCompatActivity {

@Override�protected void onCreate(Bundle savedInstanceState) {�super.onCreate(savedInstanceState);�setContentView(R.layout.activity_main);�Button btn = (Button) findViewById(R.id.btn);�btn.setOnClickListener(new View.OnClickListener() {� @Override� public void onClick(View v) {� startActivity(new Intent(MainActivity.this, SecondActivity.class));� }� });� }�}

MainActivity.java

27 of 31

  • Now show two fragments in the second activity, so for that need to create two layouts for the fragments, pretty simple layouts with a text view in each layout.

<?xml version="1.0" encoding="utf-8"?>�<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"�...>

<TextView�android:layout_width="wrap_content"�android:layout_height="wrap_content"�android:textAppearance="?android:attr/textAppearanceLarge"�android:text="This is the Top Fragment"�android:id="@+id/textView"�android:layout_gravity="center" />�</LinearLayout>

top_fragment.xml and bottom_fragment.xml

28 of 31

  • For the fragments, first need a class, so created a class which extends Fragment class and simply set its content to the layout files.

package androidhunger.activityfragmentintentdemo;

import android.app.Fragment;�....

public class TopFragment extends Fragment{�@Override�public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {�View view = inflater.inflate(R.layout.top_fragment,container,false);�return view;�}�}

TopFragment.java and BottomFragment.java

29 of 31

  • In the second activity just wanted to show two fragments which is just created above, so in its layout file, Finally add the two fragments.

<?xml version="1.0" encoding="utf-8"?>�<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"�xmlns:tools="http://schemas.android.com/tools"�android:layout_width="match_parent"�android:layout_height="match_parent"�.....">

<fragment�android:layout_width="wrap_content"�android:layout_height="wrap_content"�android:name="androidhunger.activityfragmentintentdemo.TopFragment"�android:id="@+id/fragment"�android:layout_alignParentTop="true"�android:layout_centerHorizontal="true"�tools:layout="@layout/top fragment" />

<fragment�android:layout_width="wrap_content"�android:layout_height="wrap_content"�android:name="androidhunger.activityfragmentintentdemo.BottomFragment"�android:id="@+id/fragment2"�android:layout_alignParentBottom="true"�android:layout_centerHorizontal="true"�tools:layout="@layout/bottom fragment" />�</RelativeLayout>

TopFragment.java and BottomFragment.java

30 of 31

OUTPUT:

31 of 31

THANK YOU….