Android MediaPlayer local music player (binding service)

Source: Internet
Author: User

This article describes the MediaPlayer local music player, and when the application is no longer in the foreground and there is no activity using it, in order to ensure that the audio continues to play, we need to establish a service.

The interaction between the activity and the binding Services service is the focus of this article (it is important to note that activity cannot directly access the methods in the service object, so we have a brief introduction, which is also for the security of services, etc.).


Directly on the code:

Layout file: Activity_main:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" > <textview android:layout_width= "match_parent" android:layout_height= "Wrap_conte NT "android:gravity=" Center_horizontal "android:text=" Turn on background service play audio "/> <linearlayout android:l Ayout_width= "Match_parent" android:layout_height= "wrap_content" android:orientation= "Horizontal" and roid:layout_margintop= "50DP" > <button android:id= "@+id/fastbackward" Android:layout_wid  Th= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:text= "Rewind"            /> <button android:id= "@+id/startservicebutton" android:layout_width= "0DP"           android:layout_height= "Wrap_content" android:layout_weight= "1" android:text= "open"/> <button android:id= "@+id/stopservicebut Ton "android:layout_width=" 0DP "android:layout_height=" Wrap_content "Android:layout_weigh t= "1" android:text= "Off"/> <button android:id= "@+id/fastforward" Android:lay Out_width= "0DP" android:layout_height= "Wrap_content" android:layout_weight= "1" android:te xt= "Fast Forward"/> </LinearLayout></LinearLayout>

Mainactivity:

Package Com.multimediademo6audioservice;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;public class Mainactivity extends Activity implements Onclicklistener {private Button Startservicebutton, Stopservicebutton, fastbackward,fastforward;private Intent intentservice;private Simpleaudioservice Simpleaudioservice;boolean flag = false; @Overrideprotected void OnCreate (Bundle savedinstancestate {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); init ();} /** * Instantiate component */private void init () {Startservicebutton = (Button) Findviewbyid (R.id.startservicebutton); Stopservicebutton = (Button) Findviewbyid (R.id.stopservicebutton); fastbackward = (Button) Findviewbyid ( R.id.fastbackward); Fastforward = (Button) FindviewbyId (R.id.fastforward); Startservicebutton.setonclicklistener (this), Stopservicebutton.setonclicklistener (this); Fastbackward.setonclicklistener (this); Fastforward.setonclicklistener (this); intentservice = new Intent (This, Simpleaudioservice.class);} @Overridepublic void OnClick (View v) {switch (V.getid ()) {/*** *) on */case R.id.startservicebutton:startservice ( Intentservice);/** * Establishes a connection to the service through a bindservice command, and the Bindservice command sets the object (* The Serviceconnection interface below) is named Serviceconnection. */bindservice (Intentservice, serviceconnection,context.bind_auto_create); flag = true;break;/** * Close */case R.ID.STOPSERVICEBUTTON:IF (flag) {Unbindservice (serviceconnection); StopService (intentservice); flag = false;} break;/** * Rewind */case r.id.fastbackward:if (flag) {Simpleaudioservice.backwardfun ();} break;/** * Fast forward */case r.id.fastforward:if (flag) {Simpleaudioservice.forwardfun ();} Break;default:break;}} /** * Serviceconnection is an serviceconnection type object that is an interface that listens to the State of the bound service */private serviceconnection serviceconnection = New SeRviceconnection () {/** * Click the Open button to invoke the Onserviceconnected method in the Serviceconnection object. * Pass a IBinder Object * to the method, which is actually created and committed from the service itself. This IBinder object will be the Simpleaudioservicebinder type and we will create it in the service. * It will have a method to return to our service itself and become getservice so that we can manipulate the object returned by the method directly. */@Overridepublic void onserviceconnected (componentname name, IBinder sasbinder) {Simpleaudioservice = (( Simpleaudioservice.simpleaudioservicebinder) sasbinder). GetService ();} /** * This method is used to handle situations when disconnected from the service. */@Overridepublic void onservicedisconnected (componentname name) {simpleaudioservice = null;}};}

Open service class: Simpleaudioservice:

Package Com.multimediademo6audioservice;import Android.app.service;import Android.content.intent;import Android.media.mediaplayer;import Android.media.mediaplayer.oncompletionlistener;import Android.os.Binder;import Android.os.ibinder;import android.util.log;/** * Open service * */public class Simpleaudioservice extends service implements OnC Ompletionlistener {private String TAG = "Zhongyao";p rivate MediaPlayer player;public class Simpleaudioservicebinder Extends Binder {simpleaudioservice getService () {return simpleaudioservice.this;}} Private final IBinder Sasbinder = new Simpleaudioservicebinder (), @Overridepublic ibinder onbind (Intent Intent) {return SA Sbinder;} /** * When you click Open in Mainactivity and call StartService to open the service, * the following two methods are called: OnCreate (), Onstartcommand ()/@Overridepublic void OnCreate () {super.oncreate (); LOG.V (TAG, "onCreate");p layer = Mediaplayer.create (this, r.raw.good);p Layer.setoncompletionlistener (this);} @Overridepublic int Onstartcommand (Intent Intent, int flags, int startid) {log.d (TAG, "onStartcommand "), if (!player.isplaying ()) {Player.start ();} Return Super.onstartcommand (Intent, flags, Startid);} /** * Call StopService when the service is stopped, the OnDestroy () method is called. */@Overridepublic void OnDestroy () {Super.ondestroy (); LOG.D (TAG, "OnDestroy"), if (player.isplaying ()) {player.stop ();} Player.release ();} /** * After play is called */@Overridepublic void Oncompletion (MediaPlayer MP) {stopself ();} /** * Service method: Rewind */public void Backwardfun () {if (player.isplaying ()) {Player.seekto (player.getcurrentposition ()-2500);}} /** * Service method: Fast forward */public void Forwardfun () {if (player.isplaying ()) {Player.seekto (player.getcurrentposition () + 2500);}}}

SOURCE Download:

Click to download the source code

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.