Android (Java) Learning Note 181:android Service application, enabling background music playback in activity

Source: Internet
Author: User

1. In Android applications, there is a class (Android.app.Service)--service that does nothave a UI. To put it simply, SErvice is a background process (background program), which allows you to implement features that do not require a UI, such as playing background music , through a background program.

Here is a routine for playing back the background music:

On the basis of the previous project, the music playback function was added to the activity.

Add a new class Voiceservice (file->new->class)to the project:

Import Android.app.Service; Import android.content.Intent; Import Android.os.IBinder;  Public class extends Service {    @Override    public  ibinder onbind (Intent Intent) {        //  TODO auto-generated method stub        returnnull;}    }

The MyService class inherits Android.app.Service, and several important concepts about Service are as follows:

1). The service object is executed in a separated process (a separate thread ), which means that the service and UI (Activity) are not executed in the same process, but instead are executed in a different process.

2). Android app is on Activity start and stop Service.

3). The overload (override) OnStart () method is started on the Service and performs the background function we want.

4). The overloaded OnDestroy () method stops the background function in execution when the Service is stopped.

The following are the specific implementations of the service:

 Packagecom.himi.game2048;Importjava.io.IOException;ImportAndroid.app.Service;Importandroid.content.Intent;ImportAndroid.media.MediaPlayer;ImportAndroid.media.MediaPlayer.OnCompletionListener;ImportAndroid.media.MediaPlayer.OnErrorListener;ImportAndroid.os.IBinder; Public classVoiceserviceextendsService {PrivateMediaPlayer MP; @Override Public voidonCreate () {//Initializing Music Resources        Try{MP= Mediaplayer.create ( This, R.raw.play_music);        Mp.prepare (); } Catch(IllegalStateException e) {//TODO Auto-generated catch blockE.printstacktrace (); } Catch(IOException e) {//TODO Auto-generated catch blockE.printstacktrace (); }        Super. OnCreate (); } @Override Public voidOnStart (Intent Intent,intStartid) {        //TODO Auto-generated method stubs//Start playing music        if(MP! =NULL) {Mp.start (); //registers the callback function, after the music has finished, the music completes the event processingMp.setoncompletionlistener (NewOncompletionlistener () { Public voidOncompletion (MediaPlayer MP) {Try{Mp.start (); } Catch(IllegalStateException e) {//TODO Auto-generated catch blockE.printstacktrace ();                        }                                    }            }); Mp.setonerrorlistener (NewOnerrorlistener () { Public BooleanOnError (MediaPlayer MP,intWhat,intextra) {                    Try{mp.release (); } Catch(Exception e) {//TODO Auto-generated catch blockE.printstacktrace (); }                    return false;                    }            }); }                Super. OnStart (Intent, Startid); } @Override Public voidOnDestroy () {//Stop the player when the service stops and release resources        if(MP! =NULL) {mp.stop ();        Mp.release (); }        Super. OnDestroy (); } @Override Publicibinder onbind (Intent Intent) {//TODO Auto-generated method stubs        return NULL; }}

At this point, a complete service is generated, followed by the start of the service in the activity.

2. Modify Androidmanifest.xml

In the Package Explorer window, find the current information profile for the Android project, named Androidmanifest.xml. This is a file that describes the "overall information" of the Android app, and each Android app project will have one. The purpose of modifying androidmanifest.xml here is to "android the application into a service category" so that the service can be driven.

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "com.himi.game2048"Android:versioncode= "1"Android:versionname= "1.0" >    <USES-SDKandroid:minsdkversion= " the"android:targetsdkversion= "+" />    <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/pciture"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >        <!--android:screenorientation= "Portrait" phone screen is upright and will not be placed horizontally -        <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name"android:screenorientation= "Portrait" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>        <ServiceAndroid:name= "Com.himi.game2048.VoiceService"android:exported= "true"android:process= ": Remote" >        </Service>    </Application></Manifest>

Android:exported:

This property is used to indicate whether the service can be invoked or interacted with by other application components. if set to True, it can be called or interacted with, otherwise it cannot. when set to False , only the component of the same application or an application with the same user ID can start or bind the service.

Android:process:

(1) If android:process is not set, the activity and service belong to the same process .

(2) If setting android:process= ": remote" means creating a global independent process. The process is shared by different applications .

(3) If you set android:process= ". Remote "means to create a process in the current application .

3. Once configured, the next step is to add the start service Code Service-startservice ()to the activity.

Add the following code in OnCreate ():

        New Intent (webtestactivity.  this, Yypservice. class );        StartService (intent);

There is a method called StartService in the Activity class:

StartService (Intent service)

Call StartService () to start a Service, except that the StartService () parameter is a "intent" type, not the class name to start. "intent" is a very similar to the "event" class, temporarily did not do in-depth research to Intent, first consider it as an "Event" to see it?

Now, you can actually play the background music in the activity, but there is a small problem, that is, the activity has been suspended or destroyed, the background music continues to play , which also shows that service and activity is two different processes, We take the tail, let the activity in OnStop the background music also stop play, reload activity of OnStop:

    @Override    protectedvoid  onStop () {        //  TODO auto-generated method Stub        new Intent (webtestactivity.  this, Yypservice. class );        StopService (intent);         Super . OnStop ();    }

Android (Java) Learning Note 181:android Service application, enabling background music playback in activity

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.