services in android example

Services in Android perform background task indefinitely, example for services are showing notifications, downloading files, indicating progress in notification bar etc… They don’t have User interface, even if you quit  application all these operations will be performed in background. Services are inherited from base class android.app.Service.

Implementation of services in Android example.

 public class NotifyServices extends Service{  
 @Override  
 public void onCreate() {  
 super.onCreate();  
 }  
 @Override  
 public void onDestroy() {  
 super.onDestroy();  
 }  
 @Override  
 public IBinder onBind(Intent intent) {  
 return null;  
 }  
 @Override  
 public int onStartCommand(Intent intent, int flags, int startId) {  
 // This method gets called, once the service is started, perform operations like notifications, downloading, uploading etc...  
 //The intent holds the data passed from activity. 
 //If background operation is time consuming, then create thread here.  
 }  
 }  


onCreate() get called once service is initiated for the first time, use this block to initialize variable, definitions etc…,

onBind() get called If any other components wants to communicate with your service.else simply return null.

onStartCommand() gets called once the service is started.

onDestroy() calls once the service is completed its process,

Declaration of service in application manifest file.

 <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">  
     <service android:name="com.example.androidserviceexample.NotifyServices"></service>  
     <activity>  
     </activity>  
 </application>  

Service runs in main thread by default, if any performing task inside is time consuming, then create a new thread.

Starting service from activity.

 Intent myIntent = new Intent(this, NotifyServices.class);  
 this.startService(myIntent);  

To get the Context use getApplicationContext() method.