Android Programming – Create a background Service

Through our Previous Articles, we have discussed Creating an Android Service and Creating a Bounded Service. These services are user interactive; means, these are foreground services. We can interact with the Services through the User Interface elements. We have another type of Android Service, which is called Background Service.

In this Article we are going to discuss Create a background Service.

Background Services are useful to do some background operations; for example, download the file in the background. Usually these Services do not have any user interactions.

IntentService class

IntentService class is used to handle the asynchronous requests. We call these requests, Intents. These Intents handle through a single background thread. All these requests, run sequentially. That means, the requests will wait until their predecessor request completes the operation.

Create a background Service

Step 1. Create our own class MyBkgrndService, which is derived from this IntentService class. This is simple to add, if we use built-in wizard from Android Studio.

Step 1.1. Once you created the Project (with a Main Activity), right click on the app folder (from left side panel); and then select New -> Service -> Service (Intent Service) menu item. Android Studio will display the “New Android Component” dialog, to allow to configure the new component.

Step 1.2. Provide the name of the class in “Class Name:” field and click on Finish button to create the class.

Step 2. Observe that, the wizard automatically creates boilerplate code to us. Below is the overridden function required to handle the requests.

@Override
protected void onHandleIntent(Intent intent)

Step 3. Now we can write our own code with in “onHandleIntent“, to handle the background service. Just I added below statement, to display a log entry; what the code do is, get the message from the intent and display the message in log entry;

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        if ( extras != null ) {
            String msg = extras.getString("Message");
            android.util.Log.d("Greeting! = ", msg);
        }
    }

Step 4. We have the background service in-place; we need to add the code to trigger the service. Below is the code it looks like; this is added in MainActivity class, which is visible to the User to enable to interact with the user interface;

    public void doStart(View v) {
        intent = new Intent(MainActivity.this, MyBkgrndService.class);
        intent.putExtra("Message", "Hello, World!");

        startService(intent);
    }

Step 5. Run the application; if everything goes fine, it will display the button, on center of the window. Click on it, and see a message “Hello, World!” displayed in Logcat window.

That proves, our background service is working fine.

[..] David

Add a Comment

Your email address will not be published.