Background Service in Android

To create a background service, first you need to add the service into your manifest file. Then, create a class that extends service. Finally, in your activity start the service,

  1. First add the following service declaration in your application manifest file.
    1. <service android:enabled="true" android:name=".MyService">   
    2. </service>   
  2. Create a New class MyService that extends Service class
    1. public class MyService extends Service {@Override  
    2.     public void onCreate()   
    3.     {}  
    4.     @Override  
    5.     public void onStart(Intent intent, int startId)   
    6.     {  
    7.         //do something   
    8.     }  
    9.     @Override  
    10.     public IBinder onBind(Intent intent)   
    11.     {  
    12.         return null;  
    13.     }  
    14. }  
  3. To start the service and stop the service.
    1. public class MyActivity extends Activity {@Override  
    2.     public void onCreate()   
    3.     {…  
    4.         startService(new Intent(this, MyService.class);  
    5.         }  
    6.   
    7.         @Override  
    8.         public void onStop()   
    9.         {…  
    10.             stopService(new Intent(this, MyService.class));  
    11.         }  
    12.     }