How To Test A Bound Service Android
In android, Service is a component which proceed an app running in the background to perform long-running operations based on our requirements. For Service, we don't have whatever user interface and it will run the apps in the groundwork like playing the music in the groundwork or handle network operations when the user in a different app.
Android Service Life Cycle
In android, the life bike of service volition follow two different paths Started or Bound.
Started Service
A service is Started when an application component, such as an activity calls startService() method. In one case it started, it will run indefinitely in background even if the component that started is destroyed.
We tin can stop the Started service by using stopService() method or the service tin finish itself by calling stopSelf() method. In android, the Started service component volition perform a single operation and it won't return whatever event to the caller.
Bound Service
A service is Leap when another awarding component calls bindService() method. The bound service runs equally long as another application component is bound to it.
We can unbind the service by calling unbindService() method based on our requirements. In android, nosotros can demark multiple components to a single service at once, but the service volition be destroyed in case all the components unbind.
Android Services Lifecycle Diagram
Following diagram shows the lifecycle of Started service, when the service created with startService() and the lifecycle of Bound service, when the service created with bindService().
To create a service, we need to create a class that extends a Service base class or one of its existing subclasses. During our service implementation, we must need to override some of the callback methods that handle the key aspects of the service lifecycle and provide the functionality that allows our components to bind to the service.
Create a Service
More often than not, in android to create a service nosotros must create a subclass of Service or use 1 of existing subclass. In android the application component such as an activity can start the service by calling startService() which results in calling the service's onStartCommand() method.
Post-obit is the elementary instance of creating a service in android application.
public grade SampleService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO write your own code
render Service.START_NOT_STICKY;
} @Override
public IBinder onBind(Intent intent) {
// TODO for communication return IBinder implementation
return zero ;
}
}
Register a Service in Manifest File
Once we create a service, we need to register that in android manifest file using <service> element similar every bit shown below.
< manifest ... >
...
< application ... >
< service android :name= ".SampleService" />
</ application >
...
</ manifest >
Start a Service
In android, the component such as an activity, service or receiver can beginning the service using startService() method. Following is the sample code snippet of starting a service using thestartService method.
Intent intent = new Intent ( this , MyService. class );
startService(intent);
Android Service Callback Methods
During the service implementation, post-obit are the callback methods that we need to override in android application.
onStartCommand()
The organisation volition invoke this method when some other component such as an activity requests the service to be started by calling startService(). When this method executed, the service will start and run indefinitely in background. If we implement this in our code, it's our responsibility to stop the service once code execution is done past calling stopSelf() or stopService() methods. In case, if we want to provide only bounden, then we don't need to implement this method.
In android, onStartCommand() method must return an integer and the integer is a value that describes how the organisation will continue the service in the effect that the system kills it.
The onStartCommand() method will return a value from one of the post-obit constants.
| Choice | Description |
|---|---|
| START_STICKY | Information technology will restart the service in case if information technology terminated and the Intent data which is passed to theonStartCommand() method is Cypher. This is suitable for the service which are not executing commands but running independently and waiting for the chore. |
| START_NOT_STICKY | Information technology will not restart the service and it is useful for the services which will run periodically. The service will restart merely when there are a pending startService() calls. Information technology'southward the best choice to avoid running a service in case if it is not necessary. |
| START_REDELIVER_INTENT | It'south aforementioned as STAR_STICY and it recreates the service, call onStartCommand() with last intent that was delivered to the service. |
onBind()
The system will invoke this method when another component wants to bind with the service by calling bindService(). During implementation of this method, we must need to provide an interface to the clients to communicate with the service past returning an IBinder object. In android, we must need to implement this method, in instance if we don't need to let bounden, then nosotros should return NULL.
onCreate()
The system volition invoke this method when the service is created initially using onStartCommand() or onBind() methods to do i-time setup procedures. In case, if the service is already running, so this method will not telephone call.
onDestroy()
The system will invoke this method when the service is no longer used and is existence destroyed. This is the last call that the service will receive and we need to implement this method in our service to clean up any unused resources such as threads, receivers or listeners.
Mostly, in android if we start a service by calling startService() method, the service volition run continuously even if the component that started service is destroyed until nosotros cease information technology past using stopService() or information technology stops itself with stopSelf().
Aforementioned way, if nosotros create a service by calling bindService() method, the service will runs every bit long as the component is bound to it. Afterwards the service is unbound from all of its clients, the arrangement will destroy it.
In android, the service life bicycle is having a set of callback methods that need to be implemented to keep a track of services status and to execute the required things in appropriate-time.
Android Skeleton Service
Following is the skeleton service that describes about each of the lifecycle methods.
package com.tutlane.services; import android.app.Service;
import android.content.Intent;
import android.bone.IBinder;
public class SampleService extends Service {
int mStartMode ; // It indicates how to behave if the service is killed
IBinder mBinder ; // interface for clients that bind
boolean mAllowRebind ; // It indicates whether onRebind should be used @Override
public void onCreate() {
// The service is being created
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a telephone call to startService()
render mStartMode ;
}
@Override
public IBinder onBind(Intent intent) {
// A client is binding to the service with bindService()
return mBinder ;
}
@Override
public boolean onUnbind(Intent intent) {
// All clients have unbound with unbindService()
render mAllowRebind ;
}
@Override
public void onRebind(Intent intent) {
// A client is bounden to the service with bindService(),
// subsequently onUnbind() has already been called
}
@Override
public void onDestroy() {
// The service is no longer used and is being destroyed
}
}
Android Services Example
Following is the example of start playing music in the background when we start a service and that music will play continuously until we stop the service in the android application.
Create a new android awarding using android studio and give names as Services. In case if you are non enlightened of creating an app in android studio check this article Android Hello World App.
Now we need to create our own custom service file MyService.coffee in \java\com.tutlane.services path to define our bodily provider and associated methods for that correct-click on your application folderà Become to Newà select Java Class and give name every bit MyService.java.
Once we create a new file MyService.java, open it and write the lawmaking like every bit shown below
MyService.coffee
parcel com.tutlane.services;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast; /**
* Created by Tutlane on 02-08-2017.
*/ public form MyService extends Service {
private MediaPlayer player ;
@Override
public IBinder onBind(Intent intent) {
return goose egg ;
}
@Override
public void onCreate() {
Toast.makeText( this , "Service was Created" , Toast. LENGTH_LONG ).evidence();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create( this , Settings.System. DEFAULT_RINGTONE_URI );
// This will play the ringtone continuously until nosotros terminate the service.
thespian .setLooping( true );
// It volition start the role player
player .beginning();
Toast.makeText( this , "Service Started" , Toast. LENGTH_LONG ).evidence();
return START_STICKY ;
}
@Override
public void onDestroy() {
super .onDestroy();
// Stopping the player when service is destroyed
thespian .stop();
Toast.makeText( this , "Service Stopped" , Toast. LENGTH_LONG ).prove();
}
}
Now open activity_main.xml file from \src\main\res\layout path and write the following lawmaking.
Activity_main.xml
<? xml version= "i.0" encoding= "utf-8" ?>
< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android :orientation= "vertical" android :layout_width= "match_parent"
android :layout_height= "match_parent" >
< Button
android :id= "@+id/btnStart"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :onClick= "startService"
android :layout_marginLeft= "130dp"
android :layout_marginTop= "150dp"
android :text= "Start Service" />
< Button
android :id= "@+id/btnstop"
android :layout_width= "wrap_content"
android :layout_height= "wrap_content"
android :onClick= "stopService"
android :layout_marginLeft= "130dp"
android :layout_marginTop= "20dp"
android :text= "Stop Service" />
</ LinearLayout >
Now open MainActivity.java file from \java\com.tutlane.services path and write post-obit to implement custom broadcast intents.
MainActivity.coffee
packet com.tutlane.services;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.bone.Bundle;
import android.view.View; public class MainActivity extends AppCompatActivity { @Override
protected void onCreate(Parcel savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
}
// Beginning the service
public void startService(View view) {
startService( new Intent( this , MyService. course ));
}
// Stop the service
public void stopService(View view) {
stopService( new Intent( this , MyService. class ));
}
}
Now nosotros demand to register our service in android manifest file (AndroidManifest.xml) using <service> attribute like as shown below.
AndroidManifest.xml
<? xml version= "1.0" encoding= "utf-8" ?> <
< manifest xmlns: android = "http://schemas.android.com/apk/res/android"
package= "com.tutlane.services" >
android :allowBackup= "true"
android :icon= "@mipmap/ic_launcher"
android :label= "@cord/app_name"
android :roundIcon= "@mipmap/ic_launcher_round"
android :supportsRtl= "truthful"
android :theme= "@style/AppTheme" >
< activeness android :name= ".MainActivity" >
< intent-filter >
< activity android :proper name= "android.intent.activeness.MAIN" />
< category android :name= "android.intent.category.LAUNCHER" />
</ intent-filter >
</ activeness >
< service android :name= ".MyService" />
</ application >
</ manifest >
Output of Android Service Example
When we run higher up example in android emulator we will go a consequence similar as shown below
If we click on Kickoff Service button, the default ringtone will start playing and information technology volition continue until nosotros finish the service. This is how we tin create, start or stop services in android applications based on our requirements.
How To Test A Bound Service Android,
Source: https://www.tutlane.com/tutorial/android/android-services-with-examples
Posted by: boydreste1954.blogspot.com

0 Response to "How To Test A Bound Service Android"
Post a Comment