Android Fragment is the part of activity, it is also known as sub-activity. There can be more than one fragment in an activity. Fragments represent multiple screen inside one activity.
Android fragment lifecycle is affected by activity lifecycle because fragments are included in activity.
Each fragment has its own life cycle methods that is affected by activity life cycle because fragments are embedded in activity.
The FragmentManager class is responsible to make interaction between fragment objects.
Android Fragment Lifecycle
The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for fragment.
| No. | Method | Description |
| 1) | onAttach(Activity) | it is called only once when it is attached with activity. |
| 2) | onCreate(Bundle) | It is used to initialize the fragment. |
| 3) | onCreateView(LayoutInflater, ViewGroup, Bundle) | creates and returns view hierarchy. |
| 4) | onActivityCreated(Bundle) | It is invoked after the completion of onCreate() method. |
| 5) | onViewStateRestored(Bundle) | It provides information to the fragment that all the saved state of fragment view hierarchy has been restored. |
| 6) | onStart() | makes the fragment visible. |
| 7) | onResume() | makes the fragment interactive. |
| 8) | onPause() | is called when fragment is no longer interactive. |
| 9) | onStop() | is called when fragment is no longer visible. |
| 10) | onDestroyView() | allows the fragment to clean up resources. |
| 11) | onDestroy() | allows the fragment to do final clean up of fragment state. |
| 12) | onDetach() | It is called immediately prior to the fragment no longer being associated with its activity. |
Android Fragment Example
Let's have a look at the simple example of android fragment.
activity_main.xml
File: activity_main.xml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" >
-
- <fragment
- android:id="@+id/fragment2"
- android:name="com.example.fragmentexample.Fragment2"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="1"
- />
-
- <fragment
- android:id="@+id/fragment1"
- android:name="com.example.fragmentexample.Fragment1"
- android:layout_width="0px"
- android:layout_height="match_parent"
- android:layout_weight="1"
- />
-
- </LinearLayout>
File: fragment1.xml
- <?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"
- android:background="#00ff00"
- >
-
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="fragment frist"
- android:textAppearance="?android:attr/textAppearanceLarge" />
-
- </LinearLayout>
File: fragment2.xml
- <?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"
- android:background="#0000ff"
- >
-
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="Second Fragment"
- android:textAppearance="?android:attr/textAppearanceLarge" />
-
- </LinearLayout>
MainActivity class
File: MainActivity.java
- package com.example.fragmentexample;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- public class MainActivity extends Activity {
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- }
File: Fragment1.java
- package com.example.fragmentexample;
-
- import android.app.Fragment;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
-
- public class Fragment1 extends Fragment {
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
-
- return inflater.inflate(R.layout.fragment1,container, false);
- }
-
- }
File: Fragment2.java
- package com.example.fragmentexample;
-
- import android.app.Fragment;
- import android.os.Bundle;
- import android.view.LayoutInflater;
- import android.view.View;
- import android.view.ViewGroup;
-
- public class Fragment2 extends Fragment {
-
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
-
- return inflater.inflate(R.layout.fragment2,container, false);
- }
-
- }
Output:
Android Service Tutorial
Android service is a component that is used to perform operations on the background such as playing music, handle network transactions, interacting content providers etc. It doesn't has any UI (user interface).
The service runs in the background indefinitely even if application is destroyed.
Moreover, service can be bounded by a component to perform interactivity and inter process communication (IPC).
The android.app.Service is subclass of ContextWrapper class.
Note: Android service is not a thread or separate process.
Life Cycle of Android Service
There can be two forms of a service.The lifecycle of service can follow two different paths: started or bound.
- Started
- Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it runs in the background indefinitely. It is stopped by stopService() method. The service can stop itself by calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.
Understanding Started and Bound Service by background music example
Suppose, I want to play music in the background, so call startService() method. But I want to get information of the current song being played, I will bind the service that provides information about the current song.
Android Service Example
Let's see the example of service in android that plays an audio in the background. Audio will not be stopped even if you switch to another activity. To stop the audio, you need to stop the service.
activity_main.xml
Drag the 3 buttons from the pallete, now the activity_main.xml will look like this:
File: activity_main.xml
- <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
-
- <Button
- android:id="@+id/buttonStart"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_centerHorizontal="true"
- android:layout_marginTop="19dp"
- android:text="Start Service" />
-
- <Button
- android:id="@+id/buttonStop"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_above="@+id/buttonNext"
- android:layout_alignRight="@+id/buttonStart"
- android:layout_marginBottom="35dp"
- android:text="Stop Service" />
-
- <Button
- android:id="@+id/buttonNext"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignLeft="@+id/buttonStop"
- android:layout_centerVertical="true"
- android:text="Next Page" />
-
- </RelativeLayout>
activity_next.xml
It is the layout file of next activity.
File: activity_next.xml
It contains only one textview displaying the message Next Page
- <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- tools:context=".MainActivity" >
-
- <TextView
- android:id="@+id/textView1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentLeft="true"
- android:layout_alignParentTop="true"
- android:layout_marginLeft="96dp"
- android:layout_marginTop="112dp"
- android:text="Next Page" />
-
- </RelativeLayout>
Service class
Now create the service implemenation class by inheriting the Service class and overridding its callback methods.
File: MyService.java
- package com.example.serviceexampleaudio;
-
- import android.app.Service;
- import android.content.Intent;
- import android.media.MediaPlayer;
- import android.os.IBinder;
- import android.widget.Toast;
- public class MyService extends Service {
- MediaPlayer myPlayer;
- @Override
- public IBinder onBind(Intent intent) {
- return null;
- }
- @Override
- public void onCreate() {
- Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
-
- myPlayer = MediaPlayer.create(this, R.raw.sun);
- myPlayer.setLooping(false);
- }
- @Override
- public void onStart(Intent intent, int startid) {
- Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
- myPlayer.start();
- }
- @Override
- public void onDestroy() {
- Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
- myPlayer.stop();
- }
- }
Activity class
Now create the MainActivity class to perform event handling. Here, we are writing the code to start and stop service. Additionally, calling the second activity on buttonNext.
File: MainActivity.java
- package com.example.serviceexampleaudio;
- import android.app.Activity;
- import android.content.Intent;
- import android.os.Bundle;
- import android.view.View;
- import android.view.View.OnClickListener;
- import android.widget.Button;
- public class MainActivity extends Activity implements OnClickListener {
- Button buttonStart, buttonStop,buttonNext;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
-
- buttonStart = (Button) findViewById(R.id.buttonStart);
- buttonStop = (Button) findViewById(R.id.buttonStop);
- buttonNext = (Button) findViewById(R.id.buttonNext);
-
- buttonStart.setOnClickListener(this);
- buttonStop.setOnClickListener(this);
- buttonNext.setOnClickListener(this);
- }
- public void onClick(View src) {
- switch (src.getId()) {
- case R.id.buttonStart:
- startService(new Intent(this, MyService.class));
- break;
- case R.id.buttonStop:
- stopService(new Intent(this, MyService.class));
- break;
- case R.id.buttonNext:
- Intent intent=new Intent(this,NextPage.class);
- startActivity(intent);
- break;
- }
- }
- }
NextPage class
Now, create another activity.
File: NextPage.java
- package com.example.serviceexampleaudio;
- import android.app.Activity;
- import android.os.Bundle;
-
- public class NextPage extends Activity {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_next);
- }
- }
Declare the Service in the AndroidManifest.xml file
Finally, declare the service in the manifest file.
File: AndroidManifest.xml
Let's see the complete AndroidManifest.xml file
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"
- package="com.example.serviceexampleaudio"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="17" />
-
- <application
- android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
- <activity
- android:name="com.example.serviceexampleaudio.MainActivity"
- android:label="@string/app_name" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <service
- android:name=".MyService"
- android:enabled="true" />
- <activity
- android:name=".NextPage"/>
- </application>
-
- </manifest>
Output:
No comments:
Post a Comment