Android Service (not with user interaction application components) case Analysis _android

Source: Internet
Author: User
Service is run in the background for an indefinite period of time and does not interact with the user to apply the component. Each service must be declared by <service> in manifest. Can be started by Contect.startservice and Contect.bindserverice.

The service, like other application components, runs in the main thread of the process. This means that if a service requires a lot of time-consuming or blocking operations, it needs to be implemented in its child threads.

two modes of service
Native service local services are used within the application.
It can be started and run until someone stops it or stops it by itself. In this way, it starts with the call to Context.startservice () and ends with the call to Context.stopservice (). It can call Service.stopself () or Service.stopselfresult () to stop on its own. No matter how many times the StartService () method is invoked, you only need to call StopService () once to stop the service.
Some of the time-consuming tasks that are used to implement the application, such as query upgrade information, do not occupy the application, such as the activity-owned thread, but rather a single-thread background execution, so the user experience is better.

Remote services are used between applications within the Android system.
It can be programmed to operate through interfaces that are defined and exposed by itself. The client establishes a connection to the service object and invokes the service through that connection. The connection is established by calling the Context.bindservice () method to invoke Context.unbindservice () shutdown. Multiple clients can be bound to the same service. If the service is not loaded at this time, bindservice () loads it first.

Can be reused by other applications, such as weather forecasting services, other applications do not need to write such a service, call the existing can.
The StartService ()/bindservice () is not completely detached.
Life cycle
Service life cycle is not as complex as the activity, it only inherited the OnCreate (), OnStart (), OnDestroy () Three methods, when we first started the service, successively called OnCreate (), OnStart () These two methods, when the service is stopped, the OnDestroy () method is executed, and it should be noted that if the service is already started, when we start the service again, the OnCreate () method is not executed, but the OnStart () is executed directly. Method.

the difference between StartService and Bindservice
1. Using the StartService () method to enable the service, there is no connection between the caller and the service, even if the caller exits, the service is still running.
If you intend to start the service using the Context.startservice () method, the service's OnCreate () method is invoked, followed by the OnStart () method, when the service is not created.
If the service has been created before the StartService () method is invoked, calling the StartService () method multiple times does not cause the service to be created multiple times, but will cause multiple calls to the OnStart () method.
Services started with the StartService () method can only call the Context.stopservice () method to end the service, and the OnDestroy () method is invoked at the end of the service.
2. Using the Bindservice () method to enable the service, the caller and the service are bound together, once the caller exits, the service is terminated, there is a "no need to live, must die at the same time" characteristics.
Onbind () The method is only invoked when the service is started with the Context.bindservice () method. This method is invoked when the caller and the service are bound, and when the caller and the service have already been bundled, calling the Context.bindservice () method multiple times does not cause the method to be invoked more than once.
When a service is started with the Context.bindservice () method, only the Onunbind () method can be invoked to dismiss the caller and the service, and the OnDestroy () method is invoked at the end of the service.
Examples of music playback using service
First look at the final effect

Code listings:
Layout file
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
android:orientation= "Vertical"
Android:layout_width= "Fill_parent"
android:layout_height= "Fill_parent"
>
<textview
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:text= "Welcome to my blog!"
Android:textsize= "16sp"/>
<textview
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
android:text= "Music playback service"/>
<button
Android:id= "@+id/startmusic"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Open music playback service"/>
<button
Android:id= "@+id/stopmusic"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Stop music playback service"/>
<button
Android:id= "@+id/bindmusic"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:text= "Bind music playback service"/>
<button
Android:id= "@+id/unbindmusic"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
android:text= "Unbind--Bind music playback service"/>
</LinearLayout>

Musicservice
Copy Code code as follows:

Package com.example.musicservice;
Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;
Import Android.os.IBinder;
Import Android.util.Log;
Import Android.widget.Toast;
public class Musicservice extends Service {
To set a label for the log tool
private static String TAG = "Musicservice";
To define a music player variable
Private MediaPlayer MPlayer;
The service does not exist to be invoked when it needs to be created, regardless of whether startservice () or Bindservice () calls the method when it is started
@Override
public void OnCreate () {
Toast.maketext (This, "Musicsevice onCreate ()"
, Toast.length_short). Show ();
LOG.E (TAG, "Musicserice onCreate ()");
MPlayer = Mediaplayer.create (Getapplicationcontext (), r.raw.music);
Settings can be played repeatedly
Mplayer.setlooping (TRUE);
Super.oncreate ();
}
@Override
public void OnStart (Intent Intent, int startid) {
Toast.maketext (This, "Musicsevice OnStart ()"
, Toast.length_short). Show ();
LOG.E (TAG, "Musicserice OnStart ()");
Mplayer.start ();
Super.onstart (Intent, Startid);
}
@Override
public void OnDestroy () {
Toast.maketext (This, "Musicsevice OnDestroy ()"
, Toast.length_short). Show ();
LOG.E (TAG, "Musicserice OnDestroy ()");
Mplayer.stop ();
Super.ondestroy ();
}
The method is invoked when other objects notify the service through the Bindservice method
@Override
Public IBinder Onbind (Intent Intent) {
Toast.maketext (This, "Musicsevice onbind ()"
, Toast.length_short). Show ();
LOG.E (TAG, "Musicserice onbind ()");
Mplayer.start ();
return null;
}
The method is invoked when other objects notify the service through the Unbindservice method
@Override
public boolean onunbind (Intent Intent) {
Toast.maketext (This, "Musicsevice onunbind ()"
, Toast.length_short). Show ();
LOG.E (TAG, "Musicserice onunbind ()");
Mplayer.stop ();
return Super.onunbind (Intent);
}
}

Mainactivy (Invoke service)
Copy Code code as follows:

Package com.example.musicservice;
Import android.app.Activity;
Import Android.content.ComponentName;
Import Android.content.Context;
Import android.content.Intent;
Import android.content.ServiceConnection;
Import Android.os.Bundle;
Import Android.os.IBinder;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.Toast;
Import Android.view.View.OnClickListener;
public class Mainactivity extends activity {
To set a label for the log tool
private static String TAG = "Musicservice";
/** called the activity is a. */
@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Output toast messages and log records
Toast.maketext (This, "musicserviceactivity",
Toast.length_short). Show ();
LOG.E (TAG, "musicserviceactivity");
Initlizeviews ();
}
private void Initlizeviews () {
Button btnstart = (button) Findviewbyid (R.id.startmusic);
Button Btnstop = (button) Findviewbyid (R.id.stopmusic);
Button Btnbind = (button) Findviewbyid (R.id.bindmusic);
Button Btnunbind = (button) Findviewbyid (R.id.unbindmusic);
Definition Click Listener
Onclicklistener OCL = new Onclicklistener () {
@Override
public void OnClick (View v) {
Displays the object specified intent is a service
Intent Intent = new Intent (mainactivity.this,musicservice.class);
Switch (V.getid ()) {
Case R.id.startmusic:
Start Service
StartService (Intent);
Break
Case R.id.stopmusic:
Stop Service
StopService (Intent);
Break
Case R.id.bindmusic:
Binding Services
Bindservice (Intent, Conn, context.bind_auto_create);
Break
Case R.id.unbindmusic:
Untied Service
Unbindservice (conn);
Break
}
}
};
Binding Point hit Monitor
Btnstart.setonclicklistener (OCL);
Btnstop.setonclicklistener (OCL);
Btnbind.setonclicklistener (OCL);
Btnunbind.setonclicklistener (OCL);
}
Define a Service link object
Final Serviceconnection conn = new Serviceconnection () {
@Override
public void onservicedisconnected (componentname name) {
Toast.maketext (Mainactivity.this, "Musicserviceactivity onsevicedisconnected"
, Toast.length_short). Show ();
LOG.E (TAG, "musicserviceactivity onsevicedisconnected");
}
@Override
public void onserviceconnected (componentname name, IBinder service) {
Toast.maketext (Mainactivity.this, "Musicserviceactivity onserviceconnected"
, Toast.length_short). Show ();
LOG.E (TAG, "musicserviceactivity onserviceconnected");
}
};
}

The final effect is:
When the first button is pressed, the service is enabled using the StartService () method, even if the service is exited, the concert continues to play. To view the running status of a program:

If you are using the Bindservice () method to enable the service, the caller and the service are bound together, and when you exit Activy, service stops.
Through StartService (), we exit the program, we can release activty resources, because the service is still running in the background, so our music can continue to play,. In this way, we can enjoy the music, while chatting QQ, or browsing the news and so on.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.