Service is one of the four components of Android and plays a very important role in Android development.
Services that start with StartService () are in the "Started" state, and once started, the service runs in the background, even if the application component that started it has been destroyed. A service that typically started a state performs a single task and does not return any results to the initiator. For example, when a file is downloaded or uploaded, the service should stop itself when the operation is complete.
There is also a "bind" state of service, which is initiated by calling Bindservice (), a bound service that provides an interface that allows the component to interact with the service, can send requests, get return results, and can interact (IPC) through the Kua process communication. A bound service can be run only after the application component is bound, and multiple components may bind to a service, and when the Unbind () method is called, the service is destroyed.
About the service life cycle:
Combined with the related content of the book, a simple music player was created to better understand the application of service communication in the actual development.
The relevant code for the service is as follows:
public class Musicservice extends Service {
Private MediaPlayer MP = new MediaPlayer ();
Private final IBinder binder = new Mybinder ();
public class Mybinder extends Binder {
Musicservice GetService () {
return musicservice.this;
}
}
@Override
Public IBinder Onbind (Intent Intent) {
return binder;
}
Private String filepath = environment.getexternalstoragedirectory () + "/storage/emulated/0/unknown-flower.mp3";
Public Musicservice () {
try {
Mp.setdatasource (filepath);
Mp.prepare ();
} catch (Exception e) {
E.printstacktrace ();
}
}
Public MediaPlayer getmp () {
Return MP;
}
public void Play () {
Mp.setlooping (TRUE);
if (Mp.isplaying () && MP! = null) mp.pause ();
else Mp.start ();
}
public void Stop () {
if (MP! = null) {
Mp.stop ();
try {
Mp.prepare ();
Mp.seekto (0);
} catch (Exception e) {
E.printstacktrace ();
}
}
}
@Override
public void OnDestroy () {
Super.ondestroy ();
if (MP! = null) {
Mp.stop ();
Mp.release ();
}
}
}
Effect
About Android Services