Thursday, 23 April 2015

Android Fragments

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.MethodDescription
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
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="fill_parent"  
  3.     android:layout_height="fill_parent" >  
  4.   
  5.     <fragment  
  6.         android:id="@+id/fragment2"  
  7.         android:name="com.example.fragmentexample.Fragment2"  
  8.         android:layout_width="0px"  
  9.         android:layout_height="match_parent"   
  10.         android:layout_weight="1"  
  11.         />  
  12.   
  13.     <fragment  
  14.         android:id="@+id/fragment1"  
  15.         android:name="com.example.fragmentexample.Fragment1"  
  16.         android:layout_width="0px"  
  17.         android:layout_height="match_parent"  
  18.         android:layout_weight="1"  
  19.          />  
  20.   
  21. </LinearLayout>  
File: fragment1.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     android:background="#00ff00"  
  7.      >  
  8.   
  9.     <TextView  
  10.         android:id="@+id/textView1"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content"  
  13.         android:text="fragment frist"  
  14.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  15.   
  16. </LinearLayout>  
File: fragment2.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="vertical"  
  6.     android:background="#0000ff"  
  7.      >  
  8.   
  9.     <TextView  
  10.         android:id="@+id/textView1"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content"  
  13.         android:text="Second Fragment"  
  14.         android:textAppearance="?android:attr/textAppearanceLarge" />  
  15.   
  16. </LinearLayout>  

MainActivity class

File: MainActivity.java
  1. package com.example.fragmentexample;  
  2.   
  3. import android.os.Bundle;  
  4. import android.app.Activity;  
  5. import android.view.Menu;  
  6. public class MainActivity extends Activity {  
  7.   
  8.     @Override  
  9.     protected void onCreate(Bundle savedInstanceState) {  
  10.         super.onCreate(savedInstanceState);  
  11.         setContentView(R.layout.activity_main);  
  12.     }  
  13. }  

File: Fragment1.java
  1. package com.example.fragmentexample;  
  2.   
  3. import android.app.Fragment;  
  4. import android.os.Bundle;  
  5. import android.view.LayoutInflater;  
  6. import android.view.View;  
  7. import android.view.ViewGroup;  
  8.   
  9. public class Fragment1 extends Fragment {  
  10.     @Override  
  11.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  12.             Bundle savedInstanceState) {  
  13.         // TODO Auto-generated method stub  
  14.         return inflater.inflate(R.layout.fragment1,container, false);  
  15.     }  
  16.   
  17. }  

File: Fragment2.java
  1. package com.example.fragmentexample;  
  2.   
  3. import android.app.Fragment;  
  4. import android.os.Bundle;  
  5. import android.view.LayoutInflater;  
  6. import android.view.View;  
  7. import android.view.ViewGroup;  
  8.   
  9. public class Fragment2 extends Fragment {  
  10.       
  11.     public View onCreateView(LayoutInflater inflater, ViewGroup container,  
  12.             Bundle savedInstanceState) {  
  13.         // TODO Auto-generated method stub  
  14.         return inflater.inflate(R.layout.fragment2,container, false);  
  15.     }  
  16.   
  17. }  


Output:

android fragment

Android Service Tutorial

android service
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.
  1. Started
  2. 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.
service lifecycle

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
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <Button  
  12.         android:id="@+id/buttonStart"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentTop="true"  
  16.         android:layout_centerHorizontal="true"  
  17.         android:layout_marginTop="19dp"  
  18.         android:text="Start Service" />  
  19.   
  20.     <Button  
  21.         android:id="@+id/buttonStop"  
  22.         android:layout_width="wrap_content"  
  23.         android:layout_height="wrap_content"  
  24.         android:layout_above="@+id/buttonNext"  
  25.         android:layout_alignRight="@+id/buttonStart"  
  26.         android:layout_marginBottom="35dp"  
  27.         android:text="Stop Service" />  
  28.   
  29.     <Button  
  30.         android:id="@+id/buttonNext"  
  31.         android:layout_width="wrap_content"  
  32.         android:layout_height="wrap_content"  
  33.         android:layout_alignLeft="@+id/buttonStop"  
  34.         android:layout_centerVertical="true"  
  35.         android:text="Next Page" />  
  36.   
  37. </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
  1. <RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:id="@+id/textView1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentLeft="true"  
  16.         android:layout_alignParentTop="true"  
  17.         android:layout_marginLeft="96dp"  
  18.         android:layout_marginTop="112dp"  
  19.         android:text="Next Page" />  
  20.   
  21. </RelativeLayout>  

Service class

Now create the service implemenation class by inheriting the Service class and overridding its callback methods.
File: MyService.java
  1. package com.example.serviceexampleaudio;  
  2.   
  3. import android.app.Service;  
  4. import android.content.Intent;  
  5. import android.media.MediaPlayer;  
  6. import android.os.IBinder;  
  7. import android.widget.Toast;  
  8. public class MyService extends Service {  
  9.  MediaPlayer myPlayer;  
  10.  @Override  
  11.  public IBinder onBind(Intent intent) {  
  12.   return null;  
  13.  }  
  14.  @Override  
  15.  public void onCreate() {  
  16.   Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();  
  17.    
  18.   myPlayer = MediaPlayer.create(this, R.raw.sun);  
  19.   myPlayer.setLooping(false); // Set looping  
  20.  }  
  21.  @Override  
  22.  public void onStart(Intent intent, int startid) {  
  23.   Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();  
  24.   myPlayer.start();  
  25.  }  
  26.  @Override  
  27.  public void onDestroy() {  
  28.   Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();  
  29.   myPlayer.stop();  
  30.  }  
  31. }  

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
  1. package com.example.serviceexampleaudio;  
  2. import android.app.Activity;  
  3. import android.content.Intent;  
  4. import android.os.Bundle;  
  5. import android.view.View;  
  6. import android.view.View.OnClickListener;  
  7. import android.widget.Button;  
  8. public class MainActivity extends Activity implements OnClickListener {  
  9.      Button buttonStart, buttonStop,buttonNext;  
  10.      @Override  
  11.      public void onCreate(Bundle savedInstanceState) {  
  12.       super.onCreate(savedInstanceState);  
  13.       setContentView(R.layout.activity_main);  
  14.   
  15.       buttonStart = (Button) findViewById(R.id.buttonStart);  
  16.       buttonStop = (Button) findViewById(R.id.buttonStop);  
  17.       buttonNext = (Button) findViewById(R.id.buttonNext);  
  18.   
  19.       buttonStart.setOnClickListener(this);  
  20.       buttonStop.setOnClickListener(this);  
  21.       buttonNext.setOnClickListener(this);  
  22.      }  
  23.      public void onClick(View src) {  
  24.       switch (src.getId()) {  
  25.       case R.id.buttonStart:  
  26.        startService(new Intent(this, MyService.class));  
  27.        break;  
  28.       case R.id.buttonStop:  
  29.        stopService(new Intent(this, MyService.class));  
  30.        break;  
  31.       case R.id.buttonNext:  
  32.        Intent intent=new Intent(this,NextPage.class);  
  33.        startActivity(intent);  
  34.        break;  
  35.       }  
  36.      }  
  37. }  

NextPage class

Now, create another activity.
File: NextPage.java
  1. package com.example.serviceexampleaudio;  
  2. import android.app.Activity;  
  3. import android.os.Bundle;  
  4.   
  5. public class NextPage extends Activity {  
  6.  @Override  
  7.  public void onCreate(Bundle savedInstanceState) {  
  8.   super.onCreate(savedInstanceState);  
  9.   setContentView(R.layout.activity_next);  
  10.  }  
  11. }  

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
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:androclass="http://schemas.android.com/apk/res/android"  
  3.     package="com.example.serviceexampleaudio"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.   
  11.     <application  
  12.         android:allowBackup="true"  
  13.         android:icon="@drawable/ic_launcher"  
  14.         android:label="@string/app_name"  
  15.         android:theme="@style/AppTheme" >  
  16.         <activity  
  17.             android:name="com.example.serviceexampleaudio.MainActivity"  
  18.             android:label="@string/app_name" >  
  19.             <intent-filter>  
  20.                 <action android:name="android.intent.action.MAIN" />  
  21.   
  22.                 <category android:name="android.intent.category.LAUNCHER" />  
  23.             </intent-filter>  
  24.         </activity>  
  25.           
  26.         <service  
  27.             android:name=".MyService"  
  28.             android:enabled="true" />  
  29.          <activity  
  30.             android:name=".NextPage"/>  
  31.     </application>  
  32.   
  33. </manifest>  


Output:

android service example output 1 android service example output 2

No comments:

Post a Comment