Using the Broadcastreceiver music player

Source: Internet
Author: User

Broadcast is the global listener for Andorid, which listens for global broadcast messages. Therefore, it is very convenient to implement communication between different components in the system. This example shows communication between activity and service by using Broadcastreceiver. The UI interface does not operate on the playback of the music. When the user is manipulating the UI, the activity simply changes the UI and broadcasts to the service. The service that receives the broadcast makes the appropriate operation according to the broadcast content. At the same time, when the service state changes, the activity will also be broadcast, activity based on the content of the broadcast to change the interface.

  The properties of the Activity are:

    New String[]{"Wish", "agreement", "beautiful New World"}    ; New string[]{"Unknown Artist", "Zhou Yi", "Wu Bai"};    TextView title, author;    Button PLAYBT, STOPBT,NEXTBT,PREVIOUSBT;    Activityreceiver myreceiver;     int status=0x11;                    // Music background status, 0x11 not played, 0x12 is playing, 0x13 paused

  The main content in the Activity is divided into four parts:

  First, get the component Interface Component ID and register the key listener event

        //Component ID GetPlayer=NewMediaPlayer (); PLAYBT=(Button) Findviewbyid (R.ID.PLAYBT); STOPBT=(Button) Findviewbyid (R.ID.STOPBT); NEXTBT=(Button) Findviewbyid (R.ID.NEXTBT); PREVIOUSBT=(Button) Findviewbyid (R.ID.PREVIOUSBT); Title=(TextView) Findviewbyid (r.id.musictitle); Author=(TextView) Findviewbyid (R.id.musicauthor); ListView=(ListView) Findviewbyid (r.id.musiclist); Playbt.setonclicklistener ( This); Stopbt.setonclicklistener ( This); Nextbt.setonclicklistener ( This); Previousbt.setonclicklistener ( This);

  Second, the Override key monitoring method

    //All button click Trigger Event@Override Public voidOnClick (View v) {Intent Intent=NewIntent ("Com,memeda.lsy.action.ctrl_action"); Switch(V.getid ()) { CaseR.id.playbt:intent.putextra ("Control", 1);  Break;  CaseR.id.stopbt:intent.putextra ("Control", 2);  Break;  CaseR.id.nextbt:intent.putextra ("Control", 3);  Break;  CaseR.id.previousbt:intent.putextra ("Control", 4);  Break;    } sendbroadcast (Intent); }

Set the broadcast intent content as "Com,memeda.lsy.action.ctrl_action"

Different broadcasts are given based on the ID of the event source that triggered the click Listener event.

  Third, the monitoring class to create activity

    //all receive broadcast event processing     Public classActivityreceiverextendsBroadcastreceiver {@Override Public voidOnReceive (Context context, Intent Intent) {intUpdate = Intent.getintextra ("Update", 1); intCurrent = Intent.getintextra ("Current", 1); if(Current >= 0) {Title.settext (titlestrs[current]);            Author.settext (Authorstrs[current]); }            Switch(update) { Case0x11: Playbt.settext (Player); Status=0x11;  Break;  Case0x12: Playbt.settext (Pause); Status=0x12;  Break;  Case0x13: Playbt.settext (Player); Status=0x13;  Break; }        }    }

Extracts the update and current data from the receiving broadcast, where update represents the playback state of the active player and, depending on that state, changes the UI. As in playback, the play key should change to the pause flag, while the play flag is the normal play flag when paused. Current means that the first song is currently playing, and theActivity needs to determine the name and author of the song that is displayed on the UI interface.

Iv. register the Radio Listener and turn on the service backend

        // registering a broadcast receiver        New activityreceiver ();         New Intentfilter ();        Intentfilter.addaction ("Com.memeda.lsy.UPDATE_ACTION");        Registerreceiver (Myreceiver, intentfilter);         // turn on the music playback background        New Intent (This, musicplay.  Class);        StartService (intent);

The intentfilter is set to "Com.memeda.lsy.UPDATE_ACTION", where the broadcast of the background needs to be sent with such intent content, theActivity To be heard by the superintendent.

The service background consists of three parts:

  One, create the audio manager, and create a listener for its playback, because we need to automatically cut songs ~

MediaPlayer MediaPlayer; MediaPlayer=NewMediaPlayer (); Mediaplayer.setoncompletionlistener (NewMediaplayer.oncompletionlistener () {@Override Public voidOncompletion (MediaPlayer MP) { current++; if(current>=3) { current=0; } Intent Intent=NewIntent ("Com.memeda.lsy.UPDATE_ACTION"); Intent.putextra ("Current", current);                Sendbroadcast (Intent);            Prepareandplay (Musics[current]); }        });

Of course, when a song is played, Current+1 goes to the next song and sends out a broadcast notification activity to change the display of the song name on the UI interface.

 Second, the creation of service broadcast monitoring method

     Public classMusicplayreceiverextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {intControl = Intent.getintextra ("Control",-1); Switch(Control) { Case1:                    if(status==0x11) {Prepareandplay (musics[current]); Play Asset Music Status=0x12; }                    Else if(status==0x12) {mediaplayer.pause (); Status=0x13; }                    Else if(status==0x13) {Mediaplayer.start (); Status=0x12; }                     Break;  Case2:                    if(status==0x12 | | status==0x13) {mediaplayer.stop (); Status=0x11; }                     Break;  Case3: Current++; if(current>=3) { current=0; }                    if(status==0x11 | | status==0x13) {mediaplayer.stop (); Status=0x12;                    Prepareandplay (Musics[current]); }                    Else if(status==0x12) {mediaplayer.stop ();                    Prepareandplay (Musics[current]); }                     Break;  Case4:                    if(current>0) { current--; }Elsecurrent=2; if(status==0x11 | | status==0x13) {mediaplayer.stop (); Status=0x12;                    Prepareandplay (Musics[current]); }                    Else if(status==0x12) {mediaplayer.stop ();                    Prepareandplay (Musics[current]); }                     Break; } Intent sendintent=NewIntent ("Com.memeda.lsy.UPDATE_ACTION"); Sendintent.putextra ("Update", status); Sendintent.putextra ("Current", current);        Sendbroadcast (sendintent); }    }

Where case1 is play/pause, Case2 is stop playing, Case3 is next, Case4 is on. After the service is completed, the background also needs to write its own changes as a broadcast to the activity to notify it to change the UI.

  Third, register the service listener

        New musicplayreceiver ();         New Intentfilter ();        Intentfilter.addaction ("com,memeda.lsy.action.ctrl_action");        Registerreceiver (musicplayreceiver,intentfilter);

Above.

  

 

Musicplayreceiver = new Musicplayreceiver ();        Intentfilter intentfilter = new Intentfilter ();        Intentfilter.addaction ("Com,memeda.lsy.action.ctrl_action"); Registerreceiver (Musicplayreceiver,intentfilter);

Using the Broadcastreceiver music player

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.