Android: how to start a service in application

Service:  is application’s component that runs in background for indefinite period of time. It is needed when application is listening for some changes/updates happen from other system/application/data etc. It is background job to get updates/changes or any other intended task to do without user interface or user interaction. Key points to note:

  • services run in the main thread of the application process, So that they won’t block other components or the user interface, they often spawn another thread for time-consuming tasks

The scenarios where the service can be used:

  • media player playing songs from background, while user is doing other activities.
  • fetch updates from network and show in updated UI
  • doing time-consuming calculation and inform UI
  • notify user if any changes in system/message etc. has been happened

How to implement service:

  1. implement your service such as MyService extends Service
  2. add service component name in AndroidManifest.xml file
  3. start the service when it is need from your application or activity

Code Sample:

public class MyAppClient extends Application
{

public MyAppClient  getInstance()
{
return _theApp;
}

//
@Override
public void onCreate ()
{
super.onCreate();
//keep reference of the application
_theApp = this;
//init the update checker thread
_checkerService = null;
//
//after logged in you may start this service
// in LoginActivity

}
//start update checker for getting updates from server
public void startCheckerService()
{
if(Session.getInstance().isLoggedin() && _checkerService==null)
{
Thread th = new Thread(new Runnable()
{
@Override
public void run()
{
_checkerService= startService(new Intent                                        (getApplicationContext(),                         UpdateCheckerService.class));
}
});
//start service
th.start();
}
}

//to notify UI Activities/ data update listeners
public void notifyUiListeners()
{
//notify registered data update listeners
}

}

public class UpdateCheckerService extends Service
{
private UpdateCheckerService _thisService;
//timer to set schedule task
private Timer _timer;
//
@Override
public void onCreate()
{
super.onCreate();
_thisService = this;
_isStarted = true;
//default in seconds
_timer = new Timer(“UpdateCheckTimer”);
_pollSecond = 1000*;
//schedule job to get updates from server
scheduleJob();
}
@Override
public void onDestroy()
{
super.onDestroy();
_timer.cancel();
}

private void scheduleJob()
{
//set delay
_pollSecond = 1000 ;
//
if(_pollSecond>0)
{
//you can set repeated task
_timer.schedule(new UpdateTask(), _pollSecond);
}
}
private class UpdateTask extends TimerTask
{
//run—jobs to execute
@Override
public void run()
{
//connect to server
//get updates
//notify update listners such as UI View
MyAppClient.getInstance().notifyUiListeners();

//if needed then re secheduleJob()
}
}
}

in AndroidManifest.xml

<application android:name=”.MyAppClient”
android:icon=”@drawable/my_client_icon”
android:label=”@string/app_name”>

<activity android:name=”.LoginActivity”
android:label=”@string/app_name”
android:theme=”@style/customTheme”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>



<service android:name=”.UpdateCheckerService”></service>
</application>

If you need details code for updating UI from background service, please contact with I can try to figure out the requirements.

if it is helpful please comments.

References:

Advertisements

About M Moniruzzaman
A passionate software engineer, have been developing applications on various platforms such as Android, iPhone, .Net (C#) technologies and web based ASP.NET, PHP, JavaScript, jQuery technologies for more than 10 years. Especially I have expertise on developing applications for Android and iPhone, as well as service oriented, client-server based applications where clients will be reside on Android/iPhone that communicate with WCF(.NET) service hosted on server. I have completed certification in Microsoft Certified Professional Developer (MCPD) on .Net 4 . I have completed my graduation in -- B.Sc. (Engineering) in Computer Science and Engineering, ShahJalal University of Science and Technology, Bangladesh. Thanks, M. Moniruzzaman (Zaman)

6 Responses to Android: how to start a service in application

  1. John says:

    Admin – could you use help with your website? Through our site you can find Outsourced Workers starting at $1/hour. They speak English, work flexible hours, and pride themselves on doing a quality job. There are Article Writers, Web Designers, Virtual Assistants, Email Response Handling, SEO Workers, & more. If interested we invite you to check out OutsourcedWorker.com . Thanks 🙂

  2. Amit says:

    Will the service object still be active if the OS kills subclassed android.app.Application object?

  3. Hi,
    From your question, it seems to me that you mean when android app such as “MyApp” killed, then service will remain active or not?

    1. If you kill “MyApp” application with following way – android.os.Process.KillPorcess(android.os.Process.MyPid())
    then service will be destroyed, since service runs on main thread on hosting process. Hence, if main application process/thread is destroyed then all its services will be destroyed.

    There are two type of service Started and Bound. They have little different behavior so you may delve into more details from http://developer.android.com/guide/topics/fundamentals/services.html

  4. ryan728 says:

    I think the Service provides two interfaces onStartCommand and onBind to do what we want, why do u do them in onCreate

  5. Mirza says:

    Thank you so much…….. i was looking for a method to start service inside the service and was having trouble getting the context but getApplicationContext() saved the day…….. thank you sooooooooooo much….

  6. Terrific article! That is the kind of info that are supposed
    to be shared around the web. Shame on the search engines for not positioning this submit upper!
    Come on over and discuss with my website .
    Thank you =)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: