Online Tutorials & Training Materials | STechies.com
Register Login

Android Service Introduction & Creating Started Service

01 Mar 2017 7:11 am || 0

What is a Service in Android? 

A Service is an application component that can perform long-running operation in the background and does not provide a use interface. 

So, a Service, you can say, it always run on the background and it has nothing to do with user interface. For example, a Service can be downloading something in the background or long running database operation in the background. Or you can say, if you want to provide some music in the background then you can use Service for that. 

Service can essentially take two forms

  1. Started Service 
  2. Bound Service. 

Started Service

A Service is Started when an application component such as an activity starts it by calling a method called startService method. And once the Service has started, it can run in background indefinitely unless and until it’s destroyed by some component

Bound Service. 

A Service is called Bound when application component binds to it by calling bindService method. 

Basic Component o Service in Android

1) To create a service in Android we need to create a subclass of Service. 

2) The most important callback method you should override are 

  • onStartCommand, 
  • onBind, 
  • onCreate method and on Destroy method

Started Service in Android application.

Please follow the steps below for creating Started Service in Android application:

Step 1) First in the blank project drag and drop two buttons and change the text of this button as Start Service and the second button text will name it as Stop Service. So we have two buttons, Start Service and Stop Service. 

Step 2) Then go to the design of this activity and in there add one more attribute, one we will call onClick attribute and start service method.

Same we want to do with the button which is Stop Service, so we will call a method, onClick, which will be a Stop service.

Step 3) Now, go to Java, mainactivity.java class 

And in there we will create these two methods which are startservice method and stopservice method

Step 4) Now after creating these two methods, create a class which will subclass from serviceclass.therefore go package,  right click here and will create a new Java class.

name the class as, for example, 'TheService'.

Step 5) Now a class called TheService will be created 

Now we have to extend from this serviceclass but once you extend from it, you will see it will show this little error with this little bulb because there is a method we must implement, so just click this bulb and just click Implement Method.

And this method we must implement is onBind. Even if we are creating a Started Service, we must implement this or overwrite this so now this error is gone.

Step 6) Now, we will just add our three more method which we should implement. First is onCreate, Second is onStartCommand and third is onDestroy

Step 7) Now once you create or implement these methods what  you can start a Service using this onStart command and you can destroy a Service using this onDestroy command, okay

So, we will do just the same therefore just delete this line and what we can do is, we can create a Toast so we know that the Service has started.

Next, what we can do here is we will return our constant here so return, and we’ll return a constant called START_STICKY

Now, what is this constant? When you press your Control button and click this constant, you will go to the definition of this constant and here you will see, 

“This mode makes sense for the things that will be explicitly started and stopped to run for arbitrary periods of time.” And that’s what we are exactly doing. So, that’s why we are returning this constant called START_STICKY here.

Step 8) And inside this onDestroy method, what we want to do is we want to display this Toast message once again. But this time we will say that the Service is Destroyed,  So, we know when Service has Started and When Service is Destroyed. 

Step 9) Now, once we have these method implemented, we will go to mainactivity.java file where we have defined our startService and stopService methods and in here, we can start the Service using our Intent object.

And once you create an object of this intent you can start service by using this intent. So, you can just pass this intent object

Same we want to do in the stopService method and this time, instead of starting the Service, we just want to stop it.

Once everything is done, we just need to do one more thing. We just need to go to manifest.xml file

 And in there inside our application, we need to create a tag called “service” and we will name this tag service as 'TheService'  because our class name is 'TheService'. And one more thing you can do here is you can add an attribute called android export and make it false. And what this will do is it’ll prevent the other apps or other activities to use this Service.


 Once everything is done, we just need to do one more thing. We just need to go to manifest.xml file

 And in there inside our application, we need to create a tag called “service” and we will name this tag service as 'TheService', because our class name is 'TheService'. And one more thing you can do here is you can add attribute called android export and make it false. And what this will do is it’ll prevent the other apps or other activities to use this Service

Now let’s run our app. So, now our app is running so when we click the Start Service button, it shows Service Started. But it’s running in the background. So, how we can check that the Service is running? 

What you can do is you can go to the settings of your phone and inside Settings-> Apps. And inside the Apps there are downloaded apps and there are running apps, so just click running apps here. And inside the apps which are running, so you will see Service Demo here.

Now, to destroy this Service, start the Service Demo, once again and click Stop Service button. And you can see Service Destroyed. And once again, go to the settings, and you will see this service is destroyed and we cannot see this service. 

Complete Code For Creating Started Service in Android

app-java-MainActivity.java

package com.example.programmingknowledge.servicedemo;

import ...
public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activty_main);
    }
    public void startService(View view){
        Intent intent = new Intent(this, theService.class);
        startService(intent);
    }
    public void stopService(View view){
        Intent intent = new Intent(this, theService.class);
        stopService(intent);
    }
    @Override
    public boolean onCreateOptionMenu(Menu menu){
        //Inflate the menu; this adds items to the action bar if it is present
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_settings)
        {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

app-java-TheService.java

package com.example.programmingknowledge.servicedemo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
 * Created by ProgrammingKnowledge on 7/26/2015
*/
public class TheService extends Service {
        @Override
    public void onCreate() {
        super.onCreate();
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(TheService.this,"Service Started",Toast.LENGTH_LONG).show();
        return START_STICKY;
    }
    @Override
    public void onDestroy() {
        Toast.makeText(TheService.this,"Service Destroyed",Toast.LENGTH_LONG).show();
    }
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

app-Manifests-AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.programmingknowledge.servicedemo" >
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".TheService"
            android:exported="false"></service>
    </application>
</manifest>

app-res-layout-activity_main.xml

<RelativeLayout xmlns="http://schema.android.com/apk/res/android"
    xmlns:tools="http://schema.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="16dp"
    tools:context=".MainActivity">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Service"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="74dp"
        android:layout_marginStart="74dp"
        android:layout_marginTop="66dp"
        android:onClick="startService" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Service"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_marginTop="28dp"
        android:onClick="stopService"  />
</RelativeLayout>

Read Next Bound Service Example in Android