Friday, 27 March 2015

How to create your own service in android ?

Creating your Own Services

The best way to understand how a service works is by creating one. The following example shows you the steps to create a simple service.  
For now, you will learn how to start and stop a service.

Creating a Simple Service

1 . Using Eclipse, create a new Android project and name it Services.

2 . Add a new class file to the project and name it Populate it with the following code:

package ​com.emergingandroidtech.Services;

import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {
​​​​public IBinder onBind(Intent arg0)
​​​​​​​​return null;
@Override ​
​​​public int onStartCommand(Intent intent, int flags, int startId)
{ ​
​​​​​​​// We want this service to continue running until it is explicitly
​​​​​​​​// stopped, so return sticky.
​​​​​​​​Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show();
​​​​​​​​return START_STICKY; ​​​​
} ​​​​

​​​​@Override ​
​​​public void onDestroy()
​Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show(); ​

3 . In the AndroidManifest.xml file, add the following statement in bold: 

<?xml ​version=”1.0”​encoding=”utf-8”?>
​​​​​​android:versionName=”1.0”> ​


​​​​​​​​​​​​​​​​​​android:label=”@string/app_name”> ​​

​​​​​​​​​​<intent-filter> ​
​​​​​​​​​​​​​​​<action ​android:name=”android.intent.action.MAIN”​/>
​​​​​​​​​​​​​​​​<category​ android:name=”android.intent.category.LAUNCHER”​/> ​​​


​​​​​​​​      <service android:name=”.MyService” />


4 . In the main.xml file, add the following statements in bold:

<?xml​ version=”1.0”​encoding=”utf-8”?>
​​​​android:layout_width=”fill_parent” ​​
​​android:layout_height=”fill_parent” ​​​​>

​​​​android:layout_height=”wrap_content” ​​
​​android:text=”Start Service” />

​​​​android:layout_height=”wrap_content” ​
​​​android:text=”Stop Service” />


5 . Add the following statements in bold to the file:

package​ com.emergingandroidtech.Services;
import​ android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.widget.Button;

public ​class​ MainActivity​ extends​ Activity

​​​​/**​ Called​ when​ the ​activity ​is ​first ​created.​*/

​public ​void​ onCreate(Bundle​ savedInstanceState)
Button btnStart = (Button) findViewById(; ​
​​​​​​​btnStart.setOnClickListener(new View.OnClickListener()
​​​​​​​​​​​​public void onClick(View v)
​​​​​​​​​​​​​​​​startService(new Intent(getBaseContext(), MyService.class)); ​
Button btnStop = (Button) findViewById(; ​
​​​​​​​btnStop.setOnClickListener(new View.OnClickListener()
{ ​​​​​​
​​​​​​public void onClick(View v)
​​​​​​​​​​​​​​​​stopService(new Intent(getBaseContext(), MyService.class));


6 . Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.

1 comment: