Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create Android services in Java

The article has the objective to make the developers aware on the process to create android services with the assistance of Java Programming language in simple steps.

How to Create Android services in Java?

We will learn today on the process to create the android services making use of the Java programming language. Also we will be taking the assistance of Eclipse and Android 4.1.

What is a service?

It is nothing but an element that runs in the background without interacting with the user. Each of the developer can come up with new Services in his application. Multitasking for Android is basically handled with the support of services for the reason that they can run in their own process. Making use of threads in Activities still connects you to the life-cycle of Activities. Also Android system may decide to suspend them at any point in point.

Talking about the Android platform, it offers pre-defined Services. This is generally exposed via a specific Manager class. The method getSystemService() can be used to gain the access to this service.

Declaring own Services

You can declare your own Service to perform long running operations without user interaction or to supply functionality to other applications.

A Service needs to be declared in the AndroidManifest.xml via a <service android:name="yourclasss"> </service> and the implementing class must extend the Service class or one of its subclasses.

A Service will not automatically run in its own thread. Without the process attribute, they run the main thread of their hosting process. Therefore you should run performance intensive tasks in the background.

Running a Services in its own process

You can also specify that your Service runs in a separate process via theandroid:process=":process_description" attribute.

This way the service gets its own process and has its own memory. Any long running operation in the Service, e.g. a garbage collection, will not affect the user interface of your Activity.

The colon prefix before the name tells Android that the Service is private to its declaring application. If the colon is not used the Service would be a global process and can be used by other components.

<service
  android:name="WordService"
  android:process=":my_process" 
  android:icon="@drawable/icon"
  android:label="@string/service_name"
  >
</service>

Application will not be blocked while running a service in its own process in case the service performs long running operations in its main thread. However there is a need to make use of some interprocess communication to communicate to your service from other parts.

Starting Services

The startService() method can be made use of by an Activity to start a Service and stop the service via the stopService() method. The bindService() method of the Service can be used to interact with the Service by the Activity. This would be requiring anServiceConnection object that permits to connect to the Service and which return a IBinder object that can be used by the activity to communicate with the Service.

Once a Service is started the onCreate() method is called and then the onStartCommand() method is called with the Intent data provided by the activity. startService() also permits the user to offer a flag that signifies the lifecycle behavior of the services.

  • Service.START_STICKY is deployed for services that are explicit started or stopped.
  • Services started withService.START_NOT_STICKY will end automatically post he completion of the onStartCommand() method.
  • A Service is started within the main thread of the application hence all long running tasks needs to be operated in the background.

Scheduling of Services

Automatically starting Services via Receivers

In order to initiate the Services automatically after the Android system starts, one can register a BroadcastReceiver to the Android android.intent.action.BOOT_COMPLETED system event. This needs theandroid.permission.RECEIVE_BOOT_COMPLETED permission.

The subsequent AndroidManifest.xml registers a receiver for the BOOT_COMPLETED event.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" />

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:icon="@drawable/icon"
        android:label="@string/app_name" >
        <activity
            android:name=".ServiceConsumerActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyScheduleReceiver" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        <receiver android:name="MyStartServiceReceiver" >
        </receiver>
    </application>

</manifest>

Talking about the onReceive() method the corresponding BroadcastReceiver would then begin the service.

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

  @Override
  public void onReceive(Context context, Intent intent) {
    Intent service = new Intent(context, WordService.class);
    context.startService(service);
  }
}

In case the application is being installed on the SD card, then it is not available after theandroid.intent.action.BOOT_COMPLETED event. One needs to Register in this case for theandroid.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE event.

Also, the point to note here is that for Android 3.0, the user requires to have initiated the application at least once before the application can receive android.intent.action.BOOT_COMPLETED events.

Scheduling of Services via AlarmManager

Similar to the Activities, the process of a service may be terminated at any time by the Android system in order to save resources. That is why one cannot simply make use of a simple TimerTask in the service to ensure that it is executed on a regular basis.

The below code would be incorrect since Android may terminate your Service.

public void onCreate() {
    super.onCreate();
    pollForUpdates();
  }

// WRONG, don't do this
private void pollForUpdates() {
  timer.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
      if (list.size() >= 6) {
        list.remove(0);
      }
      list.add(fixedList[index++]);
      if (index >= fixedList.length) {
        index = 0;
      }
    }
  }, 0, UPDATE_INTERVAL);
  Log.i(getClass().getSimpleName(), "Timer started.");
}

Pending Intent

This is nothing but a token that is being given to another application. The example includes Notification Manager, Alarm Manager or any other third party application that would allow the other application to make use of the the permissions of your application to execute a predefined piece of code.

In order to perform a broadcast with a pending intent, obtain a PendingIntent via PendingIntent.getBroadcast(). One receives the activity via PendingIntent.getActivity() to perform an activity via pending intent.



Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login