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

Android Services: How to create your own services in Android

In this article we will learn how to create our own services and use them to perform background tasks asynchronously.

We know that every operating system is controlled via Service protocol process. Basically a service is a standard application in the Android System that runs in the background without demanding to cooperate with the manipulator or the user. After the illustration, while consuming system application, here we might want to perform particular background music with equivalent time consumption. In such circumstance, the code that is playing the background composition has no need to interact with the manipulator or the user, and these types of the processes can successfully be run as a service process system. These Android Services are also perfect for those types of situations in which there is no requirement to display a User Interface to the users. A very well and standard illustration of this consequence is a submission that constantly logs the environmental coordinates of the devices. In those types of situations we can also write a service, which is used to work in the system background.

Generally we all are aware that the services are very important and interrelated with our programming segment logic, especially in case of the operating system. We have to take a clear and standard way of following services.

The subsequent sections will add more functionality to this services. Now we talk about some methods that are very much interrelated with our service program binding.

Sl.

Services

Application of User Interface

1

Creating a service

To Create a specific class and extend the Service class.

2

Implementing the methods

in a service

Basically the following methods are implemented in the service

i) onBind()

ii) onStartCommand()

iii) onDestroy ().

3

Executing tasks on a separate thread

and auto-stopping a service

This is also very popular of the IntentService class.

4

Starting a service

When we start the services then we use the startService() method.

5

Performing repeated tasks

Some time it requires repeated task so use the Timer class and call its scheduleAtFixedRate () method.

6

Allowing the communication between

an activity and a service

Generally the use of the Intent objects is to pass the data into the service system. Generally the service and the broadcast are used to notify an activity.

7

Stopping a service

When we start the process then it must be stopped, so in that circumstance use the stopService () method.

8

Binding an activity to a service

The Binder class is in our service. Itimplements the ServiceConnection class in our calling activity.

9

Performing long-running tasks

The AsyncTask class implements three methods

i) doInBackground()

ii) onProgressUpdate()

iii) onPostExecute()

10

Updating the UI from a

Runnable block

The post () method of a view is used to update the UserInterface. Alternatively we can also use a Handler class.

Table1: Showing services

Now we will discuss some processes which are used to start services and stop services. Here we are using Eclipse software that is responsible to create a new Android project and name it Services. The step by step process is given below.

Step: 1: At first we add a new Java Class file to the project and give a name BCEIService. And Populate the BCEIService.java file with the following code.

Listing 1: Sample showing service implementation

  package net.BCEIAndroid.Services;
import android.app.Service;	//import the services apps
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class BCEIService  extends Service 
{
@Override
public IBinder onBind(Intent args[]) 
{
return null; // return null
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) 
{
/* Here we want this types of service to continue running until it is explicitly (not directly) stopped for that reason return statement is use with sticky.*/
Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() // this destroy function
{
super.onDestroy();
Toast.makeText(this, “Here the Service is Destroyed”, Toast.LENGTH_LONG).show();
}
}

  

After completing the first step we just go to the 2nd step.

Step2: Basically the following code AndroidMainfest.xml file is used to store configuration details.

  <?xml version=”1.0” encoding=”utf-8”?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”net.bcei.Services”
android:versionCode=”1”
android:versionName=”1.0” >
<uses-sdk android:minSdkVersion=”14” />
<application
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name” >
<activity
android:label=”@string/app_name”
android:name=”.ServicesActivity” >
<intent-filter >
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<service android:name=”.BCEIService” />
</application>
</manifest>

  

Step3: After the above job we just think about the main.xml file. Now we add the following code here.

  <?xml version=”1.0” encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”vertical” >
<Button android:id=”@+id/btnStartService”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Start The Services…..”
android:onClick=”startService”/> //start service process
<Button android:id=”@+id/btnStopService”
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”Stop the Services…….”
android:onClick=”stopService” /> //stop services process
</LinearLayout>

  

Step 4: Now we are going to the 4th step process. In Step four we just add the below statements in the ServicesActivity.java file:

  package net.learn2develop.Services;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class serviceactivity extends Activity 
{
/** This system is calling when the activity is first created here. */
@Override
public void onCreate(Bundle savedInstanceState)
 {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void startService(View view)
 {
startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view) 
{
stopService(new Intent(getBaseContext(),
MyService.class));
}
}

  

Step 5: After writing the above code, we just press F11 to debug the application on the Android emulator systems.

Step 6: The sixth step is used for the start and stop of services protocol. Basically this illustration is used to start and stop the application services. It is true that the service itself is not doing anything very useful. But if we illustrate the service as a step by step process then we first define a class that extends the Service of the base class.

Start Service button will start the service and clicking on the Stop Service button will stop the services. After the processing of the above program it is important to note that .

  • Point should be remembered that all services extend the Services class
  public class BCEIService extends Service 
  {
              
  }
  

Here also locate the BCEIService class. We can implement the three methods in that platform

  Method: 1
  @Override
  public IBinder onBind(Intent arg0) 
  { 
           
  }
   
  Method: 2
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) 
  { 
             
  }
   
  Method: 3
  @Override
  public void onDestroy() //This is destroy function
  { 

  }
  

Generally here we can use different types of methods. One of them is onBind () method which empowers us to bind an activity to a service process. This in turn enables an activity that is to straight line access members and the methods inside a service. Now we can simply return a null for this method. The onStartCommand () method is called when we start the service explicitly using the startService () method. This method signifies the start of the service, and we code it to do the things we need to do for our service. In this method we returned the constant START_STICKY so that the service will continue to run until it is explicitly stopped.

The onDestroy () method is called when the service is stopped using the stopService () method. There are different types of processes that are used to clean up the resources used by our service system. All the services that we have fashioned must be declared in the Android Manifest.xml file which is basically like the following method

Listing 2: Sample showing configuration

  <service android:name=”.BCEIService”/>
If we have any obligatory we want our service to be available to other applications then we can always add an intent filter with an action name in the following manner
<service android:name=”.BCEIService”>
<intent-filter>
<action android:name=”net.BCEIAndroid.Services.BCEIService”/>
</intent-filter>
</service>

  

Now here we want to start a service. In general we use the startService() method by following process or protocol.

startService(new Intent(getBaseContext(), BCEIService.class));
  

If we are calling this service from an external application, then the call to the startService() method generally looks like the following.

  startService(new Intent(“net.BCEIAndroid.Services.BCEIService”));
  

In that way if we want to stop the starting service, then we use the stop service method stopService() method.

  stopService(new Intent(getBaseContext(), BCEIService.class));
  

How to establish communication between a service and an activity

Often the service is totally dependent on the thread system process. It also simply executes in its own thread criteria and independently of the activity that calls it. This is not assert any type of problem if we simply want the service to perform some tasks sporadically and the movement does not require to be warned about the servicing status attribute. After that we illustrate a way where a service intermittently logs to the geographical location of the device to a database system. In that type of situation, there is no requirement for our service to interact with any types of activities.

Here we have just created the following program and added into the service project.

BCEIIntentService.java file

Listing 3: Sample showing IntentService implementation

  package net.BCEIAndroid.Services;
import java.net.MalformedURLException;
import java.net.URL; //set uniform resource locator
import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

public class BCEIintentservice extends IntentService 
{
public BCEIIntentService() 
{
super(“BCEIIntentServiceName………..”); /*calling base class constructor*/ 
}
@Override
protected void onHandleIntent(Intent intent)
{
try
{
// Use any site URL where some PDF document can be downloaded.
int result =DownloadFile(new URL(“http://www.testsite.com/brochure.pdf”));
Log.d(“IntentService”, “Downloaded “ + result + “ bytes”);
/* this point should be send a broadcast to inform the activity process*/
/* Process to that the file has been downloaded */
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(“FILE_DOWNLOADED_ACTION”);
getBaseContext().sendBroadcast(broadcastIntent);
}
 catch (MalformedURLException e) 
{
/*If exception will be occur then system generate the following code */
e.printStackTrace();   
	}
}
private int DownloadFile(URL url) //passing the url through the parameter
{
try 
{
/*Act out taking some time to download a file*/
Thread.sleep(5000); // Set value of thread in millisecond
}
 catch (InterruptedException e)
 {
/*This system is Auto generated catch block*/
e.printStackTrace();
}
return 100; 
}
}

  

Again we can generate another program and add the code in the ServicesActivity.java file scenario model.

Listing 4: Sample showing activity

 package net.BCEIAndroid.Services; //this is package name
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class Sevsacivity extends Activity 
{
IntentFilter intentFilter;
/* called when the activity is first loaded or created in our system. */
@Override
public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public void onResume() 
{
/*Basically super is base class constructor calling methodology */
super.onResume(); 
/*intent to filter for file downloaded intent-*/
intentFilter = new IntentFilter();
intentFilter.addAction(“FILE_DOWNLOADED_ACTION”);
/*This part is use for receiving the register ---*/
registerReceiver(intentReceiver,intentFilter);
}
@Override
/* If we want to stop my services for sudden time then use pause*/ 
public void onPause()
{
super.onPause();
		/*unregister the receiver*/
unregisterReceiver(intentReceiver);
}
public void startService(View view) 
{
startService(new Intent(getBaseContext(), BCEIService.class));
/*otherwise we can use the following code*/
/*startService(new Intent(“net.BCEIAndroid.Services”));*/
startService(new Intent(getBaseContext(), BCEIIntentService.class));
}
public void stopService(View view) 
{
stopService(new Intent(getBaseContext(), BCEIService.class));
}
private BroadcastReceiver intentBroadReceiver = new BroadcastReceiver() 
{
@Override
public void onReceive(Context context, Intent intent) 
{
Toast.makeText(getBaseContext(), “File downloading from here…”,
Toast.LENGTH_LONG).show();
}
};
}

  

After the writing the above code we just press F11 to debug the application on the Android emulator like eclipse. If the program is running successfully then we just click the Start Service button. After about five or six seconds the above program displays a message that indicates that the file has been downloaded successfully.

How to perform long-running tasks in a service

In the previous section we have discussed some code which does not do anything useful in the long term process. So we will modify it to accomplish the task in the following way.

Here we also generate the code as shown below.

Listing 5: Sample showing long running tasks

  package net.BCEIAndroid.Services; //this is package name
  import java.net.MalformedURLException;
  import java.net.URL; //set Uniform resource locator namespace
  import android.app.Service;
  import android.content.Intent;
  import android.os.IBinder;
  import android.widget.Toast;
  public class BCEIService extends Service 
  {
  @Override
  public IBinder onBind(Intent arg) 
  {
  return null; //return null information
  }
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) 
  {
  /* we want this service to endure until it is unambiguously stopped.*/
  Toast.makeText(this, “Service is Started here”, Toast.LENGTH_LONG).show();
  try 
  {
  int result = DownloadFile(new URL(“http://www.testsite.com/bcei.pdf”));
  Toast.makeText(getBaseContext(),“Downloaded “ + result + “ bytes”,
  Toast.LENGTH_LONG).show();
  }
   catch (MalformedURLException e)
   {
  /* this is Auto-generated catch block find some unexpected error*/
  e.printStackTrace();
  }
  return START_STICKY; /* here this return statement*/
  }
  private int DownloadFile(URL url) 
  {
  Try
   {
  //---This part reproduce to taking some time to download a file---*/
  Thread.sleep(5000);
  }
   catch (InterruptedException e) 
  {
  e.printStackTrace();
  }
  /* Here we return an arbitrary number representing the size of the file downloaded*/
  return 100;
  }
  @Override
  public void onDestroy() //stop the services 
   {
  super.onDestroy();
  Toast.makeText(this, “Service is Destroyed”, Toast.LENGTH_LONG).show();
  }

After writing the program just press F11 for debugging the application through the Android emulator.

Conclusion

Overall, the service management takes a major role at the development of the operating system. In this article we have discussed some types of servicing logic step by step. So the developers can easily understand the types of services and how he/she can use it easily in their own system. There are different types of methods available which are also implemented in our services mainly the start and the end service. However, keep in mind that when we install our own apps then we must set up the services also. If the app is not required then we can set the services either manually or automatically. Set automatic if the service is most important and set manual for less important services. So we can conclude that the services must be interrelated with Thread priority. Without the thread priority concept the service process is totally void.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

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