Android Learning Notes (2) ———— Android four component bis (Service) __android

Source: Internet
Author: User
Tags stub

/********************************************************************************************
* author:conowen@ Big Bell
* e-mail:conowen@hotmail.com
* Http://blog.csdn.net/conowen
* Note: This article for the original, only as a learning exchange use, reproduced please indicate the author and source.
********************************************************************************************/

1, first service such as Windows below the services are similar, no user interface, just work in the background.


2, look at the relationship of service inheritance


3,the service itself can not start, to invoke other methods to start the service. There are two different ways

A, Context.startservice ()

When using this method, the service is not related to the initiator, but simply to start the service, if the initiator quit, the service is still running in the background.

(such as music playback, even if you quit the program, the music is still playing)


B, Context.bindservice ()

When using this method, as the name implies, the initiator and service are bound together, the initiator exits, the service also stops.


4,service life cycle


A, a service initiated with the StartService () method can only call the StopService () method to end the service, and the OnDestroy () method is automatically invoked at the end of the service.

b, a service that starts with the Bindservice () method can invoke the Unbindservice () method to bind, and when invoked, it also causes the system to automatically invoke the Onunbind () and OnDestroy () methods of the service.


Life cycle of the Context.startservice mode: at
startup, call the OnStart method when the StartService method –>oncreate () –> StopService () is stopped ()
- > OnDestroy ()

life cycle of//context.bindservice mode:
binding, calling Bindservice method  ->oncreate () –> onbind ()
the Unbindservice Method –>onunbind () –> ondestory () is invoked at the time of the binding (

Service life cycle method is less than activity, only OnCreate, OnStart, OnDestroy.


5, simple music playback examples

MP3 file in the Res directory in the raw directory, drag the mp3 file to go in. (Raw for oneself new)

File format is MP3 and ogg, file name is 0~9 or a~z, the bit rate is better than or equal to 320KPS

The first activity package conowen.szu.Service;
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.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;

Import Android.widget.Toast;  The public class Serviceactivity extends activity {/** called the ' when the ' is the ' The activity ' is a./@Override public void
		OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
		Setcontentview (R.layout.main);
		Button play = (button) Findviewbyid (R.id.play);
		Button stop = (button) Findviewbyid (r.id.stop);
		Button bind = (Button) Findviewbyid (R.id.bind);
		Button unbind = (Button) Findviewbyid (R.id.unbind);
		Final Intent Intent = new Intent (serviceactivity.this,musicservice.class); Define intent as final, global variable, for the following two anonymous inner classes (onclicklisenter) using Play.setonclicklistener (new ONCLICklistener () {@Override public void OnClick (View v) {//TODO auto-generated Method stub StartService (inte
				NT);
		Start playing, through the previously defined Intent Pass}}); Stop.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated
				Method stub StopService (intent);
Stop playback}}); /******************************* Following is the Bindservice way to start service*****************************************/final Serviceconnection conn=new serviceconnection () {//global variable final, used by the following two internal classes @Override public void Onservicedisconnec Ted (componentname name) {//TODO auto-generated Method Stub toast.maketext (Serviceactivity.this, "Bind succeeded", Toast.le	
				
			Ngth_long). Show (); @Override public void onserviceconnected (componentname name, IBinder service) {//TODO auto-generated met
				
			Hod stub toast.maketext (Serviceactivity.this, "untied Success", Toast.length_long). Show ();
		}
		}; When using Bindservice to start Service,service and execute BindserThe Vice activity binding succeeds in calling Serviceconnection;//Similarly, when the service and the client using the service are unbound, the onservicedisconnected is invoked// Serviceconnection (conn) is also a parameter bind.setonclicklistener for the following Bindservice and Unbindservice (new Onclicklistener () {@Overrid e public void OnClick (View v) {//TODO auto-generated Method Stub Bindservice (intent, Conn, context.bind_auto_

			CREATE);
		}

		}); Unbind.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) {//TODO Auto-gener
				
				
			Ated method Stub unbindservice (conn);
	}
		}); }
}

The second class is a service processing method that uses a variety of service methods to achieve different functions.


The second class package conowen.szu.Service;
Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;

Import Android.os.IBinder;
	public class Musicservice extends Service {MediaPlayer player;
		New player @Override public void OnCreate () {//TODO auto-generated Method Stub super.oncreate ();
		Player = Mediaplayer.create (this, r.raw.lt26);
		Player.setlooping (TRUE); The first lifecycle of both methods is OnCreate ()} @Override public void OnStart (Intent Intent, int startid) {//TODO auto-generated Meth
		OD stub super.onstart (intent, Startid);

	Player.start ();
		@Override public IBinder onbind (Intent Intent) {//TODO auto-generated Method Stub Player.start ();
	return null;
		@Override public boolean onunbind (Intent Intent) {//TODO auto-generated the method stub player.stop ();
	return Super.onunbind (Intent);
		@Override public void OnDestroy () {//TODO auto-generated Method Stub Super.ondestroy ();
	Player.stop ();
 }

}
Effect Chart:


6,

Note: The second Java file

public class Musicservice extends Service {
If you inherit a service, you have to open the service in Androidmanifest.

   <service
            android:label= "Player"
            android:name=. Musicservice ">
         
        </service>
If the first Java file inherits an activity, the androidmanifest is

   <activity
            android:label= "Player"
            android:name=. Musicservice ">
         
        </activity>


/********************************************************/

For each more click on the "Play" button, the music will play more than one. (All of the same music, but the playback start time is different)

You can put the Player.start () method inside the OnCreate, so that even if you click the "Play" button, it's OK. Because the OnCreate method of the service will only be invoked once.

As shown in the following code (only "play" and "Stop function") do not add bindings and unbind

OnStart method does not need to write


Package conowen.szu.Service;

Import Android.app.Service;
Import android.content.Intent;
Import Android.media.MediaPlayer;
Import Android.os.IBinder;

public class Musicservice extends Service {
	MediaPlayer player;

	@Override public
	void OnCreate () {
		//TODO auto-generated method Stub
		super.oncreate ();
		Player = Mediaplayer.create (this, r.raw.lt26);
		Player.start ();
	}

	Player.start () in the OnCreate method, many times click play button, as normal playback, that is, music will not open more than one.
        //If Play.start () in the onstart aspect, not once more click the Play button, it will be played more than once, the same music play at the same time (start different)

	@Override public
	IBinder Onbind (Intent Intent) {
		//TODO auto-generated method stub return
		null;
	}


	@Override public
	void OnDestroy () {
		//TODO auto-generated method Stub
		Super.ondestroy ();
		Player.stop ();
	}








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.