Write your own Background Service in Android

Service: is one of core component of Android.

Service have not any user interface, like dialogboxe or buttons etc. Service runs in background. We use service for long process like fetch long (time consuming) data from network, play sound in background or some process where user interaction is not necessary.

For long process we can also use thread or AsyncTask but these are affected by Activity lifecycle, But Service is not affected by Activity lifecycle Service have its own life cycle.

Create new project in eclipse (Android-First-Programm).

Create new class by Right click on package that is in src folder, select new and click on Class

create new class in android eclipse

I write class name “AndroidService” and click on finish

For Service we must be inherit (extends) Service class

Now class name must be underline by red line. If we take cursor on class name it will ask to “Add unimplemented methods” your “AndroidService” class code will be like this, or write these methods by yourself.

For service add below bold line in Manifest.xml

Use two buttons in layout to start or stop service, so “activity_main” will be like this

And main MainActivity will be used to start or stop service.