Sunday, December 23, 2012

Service LifeCycle

A service is an application component that can run some long running task in the background without the need for a user interface. Some other application component can start the service and this service will then keep on running even if the user switches to another application.

A service can essentially take two forms:


Unbounded
A service is "started" when an application component (such as an activity) starts it by calling startService(). Once started, a service can run in the background indefinitely (unbounded), even if the component that started it is destroyed. Usually, a started service performs a single operation and does not return a result to the caller. For example, it might download or upload a file over the network. When the operation is done, the service should stop itself.


Bound
A service is "bound" when an application component binds to it by calling bindService(). A bound service offers a client-server interface that allows components to interact with the service, send requests, get results, and even do so across processes with interprocess communication (IPC). A bound service runs only as long as another application component is bound to it. Multiple components can bind to the service at once, but when all of them unbind, the service is destroyed.



As you can see in diagram there some method in  Unbounded service class for life cycle :


startService(Intent Service)
This you must call to start un-bounded serviec

onCreate()
This method is Called when the service is first created

onStartCommand(Intent intent, int flags, int startId)
This method is called when service is started

onBind(Intent intent)
This method you must call if you want to bind with activity

onUnbind(Intent intent)
This method is Called when the service will un-binded from activity

onRebind(Intent intent)
This method is called when you want to Re-bind service after calling un-bind method

onDestroy()
This method is called when The service is no longer used and is being destroyed


Let's create a small app to understand this..

-------------------------------------------
App Name: ServiceLifeCycle
Package Name: com.sunil
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------

MyActivity.java

  1. package com.sunil;  
  2.   
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.view.View;  
  8. import android.view.View.OnClickListener;  
  9. import android.widget.Button;  
  10.   
  11. public class MyActivity extends Activity   
  12.                     implements OnClickListener {  
  13.     private final static String TAG = "In this method: ";  
  14.     private Button startSerivce = null;  
  15.     private Button stopSerivce = null;  
  16.   
  17.     @Override  
  18.     public void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.main);  
  21.   
  22.         startSerivce = (Button) findViewById(R.id.buttonStart);  
  23.         startSerivce.setOnClickListener(this);  
  24.         stopSerivce = (Button) findViewById(R.id.buttonStop);  
  25.         stopSerivce.setOnClickListener(this);  
  26.     }  
  27.   
  28.     @Override  
  29.     public void onClick(View v) {  
  30.         if (startSerivce == v) {  
  31.             Log.i(TAG, "Activity starting service..");  
  32.             Intent serviceIntent = new Intent(this, MyService.class);  
  33.             startService(serviceIntent);  
  34.         } else {  
  35.             Intent in = new Intent(this, MyService.class);  
  36.             in.setAction("stop");  
  37.             stopService(in);  
  38.         }  
  39.     }  
  40. }  

MyService
  1. package com.sunil;
  2. import android.app.Service;  
  3. import android.content.Intent;  
  4. import android.os.IBinder;  
  5. import android.util.Log;  
  6. import android.widget.Toast;  
  7.   
  8. public class MyService extends Service {  
  9.   
  10.     private final static String TAG = "In this method: ";  
  11.     int mStartMode; // indicates how to behave if the service is killed  
  12.     IBinder mBinder; // interface for clients that bind  
  13.     boolean mAllowRebind; // indicates whether onRebind should be used  
  14.   
  15.     @Override  
  16.     public void onCreate() {  
  17.         Log.i(TAG, "Service created");  
  18.         // The service is being created  
  19.     }  
  20.   
  21.     @Override  
  22.     public int onStartCommand(Intent intent, int flags, int startId) {  
  23.         Log.i(TAG, "Service started");  
  24.           
  25.         Toast.makeText(getBaseContext(), "Service has been started..",  
  26.                 Toast.LENGTH_SHORT).show();  
  27.         return mStartMode;  
  28.     }  
  29.   
  30.     @Override  
  31.     public IBinder onBind(Intent intent) {  
  32.         // A client is binding to the service with bindService()  
  33.         Log.i(TAG, "Service binded");  
  34.         return mBinder;  
  35.     }  
  36.   
  37.     @Override  
  38.     public boolean onUnbind(Intent intent) {  
  39.         // All clients have unbound with unbindService()  
  40.         Log.i(TAG, "Service un-binded");  
  41.         return mAllowRebind;  
  42.     }  
  43.   
  44.     @Override  
  45.     public void onRebind(Intent intent) {  
  46.         // A client is binding to the service with Re-bindService(),  
  47.         // after onUnbind() has already been called  
  48.         Log.i(TAG, "Service re-binded");  
  49.     }  
  50.   
  51.     @Override  
  52.     public void onDestroy() {  
  53.         // The service is no longer used and is being destroyed  
  54.         Log.i(TAG, "Service destroyed");  
  55.   
  56.     }  
  57.   
  58. }  

main.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent"  
  7.     android:gravity="center">  
  8.     <LinearLayout  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_width="match_parent"  
  11.         android:id="@+id/linearLayout1"  
  12.         android:gravity="center">  
  13.         <Button  
  14.             android:layout_height="wrap_content"  
  15.             android:layout_width="wrap_content"  
  16.             android:id="@+id/buttonStart"  
  17.             android:text="Start Service"></Button>  
  18.         <Button  
  19.             android:layout_height="wrap_content"  
  20.             android:layout_width="wrap_content"  
  21.             android:id="@+id/buttonStop"  
  22.             android:text="Stop Serivce"></Button>  
  23.     </LinearLayout>  
  24. </LinearLayout>  

AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest  
  3.     xmlns:android="http://schemas.android.com/apk/res/android"  
  4.     package="com.sunil"  
  5.     android:versionCode="1"  
  6.     android:versionName="1.0">  
  7.     <uses-sdk android:minSdkVersion="8" />  
  8.   
  9.     <application  
  10.         android:icon="@drawable/icon"  
  11.         android:label="@string/app_name">  
  12.         <activity  
  13.             android:name=".MyActivity"  
  14.             android:label="@string/app_name">  
  15.             <intent-filter>  
  16.             <action android:name="android.intent.action.MAIN" />  
  17.             <category android:name="android.intent.category.LAUNCHER" />  
  18.             </intent-filter>  
  19.         </activity>  
  20.   
  21.         <service  
  22.             android:enabled="true"  
  23.             android:name=".MyService">  
  24.             <intent-filter>  
  25.             <action android:name="com.sunil.MyService">  
  26.             </action>  
  27.             </intent-filter>  
  28.         </service>  
  29.   
  30.     </application>  
  31. </manifest>  

The output Screen will be like this..



You can download the complete source code zip file here : ServiceLifeCycle

Cheers!!

I'd love to hear your thoughts!

Activity Lifecycle

I�m just starting with Android App Development, and if you are a beginner like me, you probably want to understand two of main concepts of Android: Activities and Intents.
After Hello World Example i wanted to know Activity Life-cycle so i learn this and sharing with you..
This is the Android Activity Life Cycle Diagram described by Google

 As you can see in diagram there 7 method in activity base class for life cycle :
onCreate(Bundle savedInstanceState)
This method is Called when the activity is first created.

onStart()
This method is Called when activity is becoming visible to the user.

onResume()
This method is Called when the activity will start interacting with the user.

onPause()
This method is Called when the system is about to start resuming a previous activity.

onStop()
This method is Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one.
    
onRestart()
This method is Called after your activity has been stopped, prior to it being started again.

onDestroy()
This method is The final call you receive before your activity is destroyed.

Other Methods:
onSaveInstanceState(Bundle outState)
This method is called before an activity may be killed so that when
it comes back some time in the future it can restore its state.

onRestoreInstanceState(Bundle savedInstanceState)
This method is called after onStart() when the activity is being
re-initialised from a previously saved state.
The default implementation of this method performs a restore of any
view state that had previously been frozen by onSaveInstanceState(Bundle).

Create a simple android app with default activity "MyActivity" then put the code like this
  1.     
  2. package com.sunil;  
  3.   
  4. import android.app.Activity;  
  5. import android.os.Bundle;  
  6. import android.util.Log;  
  7. import android.widget.Toast;  
  8.   
  9. public class MyActivity extends Activity {  
  10.  private final static String TAG="In this method: ";  
  11.       
  12.  @Override  
  13.     public void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.main);  
  16.         Toast.makeText(this"onCreate", Toast.LENGTH_SHORT).show();  
  17.         Log.i(TAG,"Activity created");  
  18.     }  
  19.    
  20.  @Override  
  21.     protected void onStart() {      
  22.     super.onStart();      
  23.     Toast.makeText(this"onStart",Toast.LENGTH_SHORT).show();  
  24.     Log.i(TAG,"Activity started and visible to user");  
  25.     }  
  26.    
  27.  @Override  
  28.     protected void onResume() {  
  29.     super.onResume();  
  30.     Toast.makeText(this"onResume", Toast.LENGTH_SHORT).show();  
  31.     Log.i(TAG,"Activity interacting with user");  
  32.  }  
  33.   
  34.     @Override  
  35.     protected void onPause() {  
  36.     super.onPause();       
  37.      Toast.makeText(this"onPause", Toast.LENGTH_SHORT).show();  
  38.      Log.i(TAG,"current activity got paused");  
  39.     }  
  40.       
  41.     @Override  
  42.     protected void onStop() {      
  43.     super.onStop();  
  44.     Toast.makeText(this"onStop", Toast.LENGTH_SHORT).show();  
  45.     Log.i(TAG," current activity got stopped");  
  46.     }  
  47.       
  48.     @Override  
  49.     protected void onRestart() {  
  50.     super.onRestart();  
  51.     Toast.makeText(this"onRestart", Toast.LENGTH_SHORT).show();  
  52.     Log.i(TAG,"activity again restarted");  
  53.     }   
  54.       
  55.     @Override  
  56.     protected void onDestroy() {      
  57.     super.onDestroy();  
  58.     Toast.makeText(this"onDestroy", Toast.LENGTH_SHORT).show();  
  59.     Log.i(TAG,"activity destored");  
  60.     }   
  61.      
  62.     @Override  
  63.     protected void onSaveInstanceState(Bundle outState) {  
  64.     super.onSaveInstanceState(outState);  
  65.     Toast.makeText(getBaseContext(),"onSaveInstanceState..BUNDLING",   
  66.       Toast.LENGTH_SHORT).show();  
  67.     Log.i(TAG,"activity data saved");  
  68.     }  
  69.       
  70.     @Override  
  71.     protected void onRestoreInstanceState(Bundle savedInstanceState) {  
  72.     super.onRestoreInstanceState(savedInstanceState);  
  73.     Toast.makeText(getBaseContext(), "onRestoreInstanceState ..BUNDLING",   
  74.       Toast.LENGTH_SHORT).show();  
  75.     Log.i(TAG,"activity previous saved data restored");  
  76.     }     
  77.       
  78. }  

and main.xml is
  1.     
  2.   
  3. <linearlayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android">  
  4. <textview android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Activity Life Cycle.." android:textsize="20sp">      
  5. </textview></linearlayout>  

the most important is AndroidManifest.xml
  1.     
  2.   
  3. <manifest android:versioncode="1" android:versionname="1.0" package="com.sunil" xmlns:android="http://schemas.android.com/apk/res/android">  
  4.     <uses-sdk android:minsdkversion="8">  
  5.   
  6.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  7.         <activity android:label="@string/app_name" android:name=".MyActivity">  
  8.             <intent-filter>  
  9.                 <action android:name="android.intent.action.MAIN">  
  10.                 <category android:name="android.intent.category.LAUNCHER">  
  11.             </category></action></intent-filter>  
  12.         </activity>  
  13.   
  14.     </application>  
  15. </uses-sdk></manifest>  

you can find the example zip file is here

cheers!!

I'd love to hear your thoughts! 

What is Android ?



Android is an operating system based on Linux with a Java programming interface for mobile devices such as smartphones and tablet computers. It is developed by the Open Handset Alliance led by Google.

Who founded Android, Inc?
Andrew E. Rubin (key person) at Open Handset Alliance.

Android, Inc. was founded in Palo Alto, California, United States in October, 2003 by Andrew E. Rubin (co-founder of Danger), Rich Miner (co-founder of Wildfire Communications, Inc.), Nick Sears (once VP at T-Mobile),and Chris White (headed design and interface development at WebTV) at Open Handset Alliance.

Google Purchased the Android
Google purchased the initial developer of the Android software, Android Inc., in 2005, making Android Inc. a wholly-owned subsidiary of Google Inc. Key employees of Android Inc., including Andy Rubin, Rich Miner and Chris White, stayed at the company after the acquisition.

Android competes with Sambian OS, Apple's iOS (for iPhone/iPad), RIM's Blackberry, Microsoft's Windows Phone (previously called Windows Mobile), and many other proprietary mobile OSes.

Android Architecture



Basically Android has the following layers:
  • applications (written in java, executing in Dalvik)
  • framework services and libraries (written mostly in java)
    • applications and most framework code executes in a virtual machine
  • native libraries, daemons and services (written in C or C++)
  • the Linux kernel, which includes
    • drivers for hardware, networking, file system access and inter-process-communication 
Android Application Components
There are four different types of application components. Each type serves a distinct purpose and has a distinct lifecycle that defines how the component is created and destroyed.

Activities
An activity represents a single screen with a user interface. 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.
An activity is implemented as a subclass of Activity.

Services
A service is a component that runs in the background to perform long-running operations or to perform work for remote processes. A service does not provide a user interface. For example, a service might play music in the background while the user is in a different application. Another component, such as an activity, can start the service and let it run or bind to it in order to interact with it.

A service is implemented as a subclass of Service.

Content providers
A content provider manages a shared set of application data. You can store the data in the file system, an SQLite database, on the web, or any other persistent storage location your application can access. Through the content provider, other applications can query or even modify the data (if the content provider allows it). For example, the Android system provides a content provider that manages the user's contact information.

A content provider is implemented as a subclass of ContentProvider.

Broadcast receivers
A broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system�for example, a broadcast announcing that the screen has turned off, the battery is low,message has been received or a picture was captured.

A broadcast receiver is implemented as a subclass of BroadcastReceiver.

Android Version history
Android Beta 
The Android beta was released on November 5, 2007, while the software developer's kit (SDK) was released on November 12, 2007.

Android 1.0
Android 1.0, the first commercial version of the software, was released on September 23, 2008. The first Android device, the HTC Dream,which was following Android 1.0 features.

Android 1.1
On February 9, 2009, the Android 1.1 update was released, initially for the T-Mobile G1 only. The update resolved bugs, changed the API and added a number of other features.

Android 1.5 ( Cupcake )
On April 30, 2009, the Android 1.5 update, dubbed Cupcake, was released, based on Linux kernel 2.6.27.

Android 1.6 ( Donut )
On September 15, 2009, the Android 1.6 SDK � dubbed Donut � was released, based on Linux kernel 2.6.29.

Android 2.0/2.1 ( Eclair )
On October 26, 2009, the Android 2.0 SDK � codenamed �clair � was released, based on Linux kernel 2.6.29.and updated on January 12, 2010 as 2.1 version.

Andrid 2.2.x (Froyo)
On May 20, 2010, the Android 2.2 (Froyo) SDK was released, based on Linux kernel 2.6.32.

Android 2.3.x ( Gingerbread )
On December 6, 2010, the Android 2.3 (Gingerbread) SDK was released, based on Linux kernel 2.6.35.

Android 3.x (Honeycomb)
On February 22, 2011, the Android 3.0 (Honeycomb) SDK � the first tablet-only Android update � was released, based on Linux kernel 2.6.36.The first device featuring this version, the Motorola Xoom tablet, was released on February 24, 2011.

Android 4.0.x (Ice Cream Sandwich)
The SDK for Android 4.0.1 (Ice Cream Sandwich), based on Linux kernel 3.0.1,was publicly released on October 19, 2011.

Android 4.1  (Jelly Bean)
Google announced the next Android version on June 27, 2012, 4.1 Jelly Bean. Jelly Bean is an incremental update, with the primary aim of improving the user interface, both in terms of functionality and performance. 

ListView in Android (Basic)

ListView: ListView is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array and converts each item result into a view that's placed into the list.

This tutorial describes how to use ListView and ListActivity in Android.

okay! so let's try this small app

 -------------------------------------------
App Name: ListViewBasic
Package Name: com.sunil
Android SDK: Android SDK 2.3.3 / API 10
Default ListActivity Name: ActivityListView
-------------------------------------------

ActivityListView.java

    package com.sunil;   

    import android.app.ListActivity; 
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.ArrayAdapter; 
    import android.widget.ListView; 
    import android.widget.Toast; 

    public class ActivityListView extends ListActivity {

     public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     // Create an array of Strings, that will be put to our ListActivity 
     String[] namesArray = new String[] { "Linux", "Windows7", "Eclipse", 
        "Suse", "Ubuntu", "Solaris", "Android", "iPhone" }; 
    
     /* Create an ArrayAdapter, that will actually make the Strings above
      appear in the ListView */ 

     this.setListAdapter(new ArrayAdapter<String>(this, 
       android.R.layout.simple_list_item_1, namesArray)); 
     } 
      @Override 
      protected void onListItemClick(ListView l, View v,  
      int position, long id) { 
     super.onListItemClick(l, v, position, id); 
      
     // Get the item that was clicked 

     Object o = this.getListAdapter().getItem(position); 
     String keyword = o.toString(); 
     Toast.makeText(this, "You selected: " + keyword,  
       Toast.LENGTH_SHORT).show(); 
     } 
    } 
 
main.xml


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

        <LinearLayout 

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

         android:orientation="vertical" 

         android:layout_width="fill_parent" 

         android:layout_height="fill_parent"> 

         <TextView 

          android:layout_width="fill_parent" 

          android:layout_height="wrap_content" 

          android:text="@string/hello" /> 

        </LinearLayout> 



    AndroidManifest.xml


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

          <manifest 

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

           package="com.sunil" 

           android:versionCode="1" 

           android:versionName="1.0"> 

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

           

           <application 

            android:icon="@drawable/icon" 

            android:label="@string/app_name"> 

            <activity 

             android:name=".ActivityListView" 

             android:label="@string/app_name"> 

             <intent-filter> 

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

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

             </intent-filter> 

            </activity> 

           

           </application> 

          </manifest> 


         
         
      The output Screen will be like this..


      You can download the complete source code zip file here : ListViewBasic 

       cheers!!

       I'd love to hear your thoughts!

       

      Copyright @ 2013 Android Developers Tipss.