How to Write a serious Android music player 2 and android music player

Source: Internet
Author: User

How to Write a serious Android music player 2 and android music player
This article describes how

Interaction with music playback Service


If you have a little experience, you know that you can put operations on the Service for a long time. How can you effectively communicate the interface with the music playback Service? In this chapter, I will give my answer, I also hope you can give us some advice.
I hope you can read this article (turn the wall on your own ):
Service API Guide: http://developer.android.com/guide/components/services.html
About bound Service in API Guide of service:
Http://developer.android.com/guide/components/bound-services.html
Service API: http://developer.android.com/reference/android/app/Service.html
 
First, implement a Service class named MainService. How should we start this Service? One Service can be started in either startService (Intent) or bindService (Intent );
The first method is suitable for the Service to complete tasks independently. For example, if you do not need to pause or cancel a download task, you can do so. However, this is a music playing application. We put the MediaPlayer in the Service to play the video. In this way, it is difficult to pause and other interactions. (In fact, this can also be done. For example, startService is used for each interaction operation. The pause command and other commands can be accessed through Intent, and the progress bar can also be sent through broadcast. But in this way, it feels ugly, and it is definitely not a conventional efficient practice );
In the second startup mode, you can obtain a Service object in onServiceConnected (which may not be a Service object, at least a handle that can access internal operations of the Service ). In this way, you can easily play and receive progress notifications. However, this method has drawbacks. Once the bound context exits, the Service will also be recycled (but the onDestory method will not be executed );
So is it simply the second startup method?
Of course this is not the case. In Google's official documents, there is no conflict between the two methods, and they are very suitable for music playing applications.
The original article is as follows:
Using A bound service
The service is created when another component (a client) CILS bindService (). the client then communicates with the service through an IBinder interface. the client can close the connection by calling unbindService (). multiple clients can bind to the same service and when all of them unbind, the system destroys the service. (The service does not need to stop itself .)
These two paths are not entirely separate. that is, you can bind to a service that was already started withstartService (). for example, a background music service cocould be started by calling startService () with anIntent that identifies the music to play. later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService (). in cases like this, stopService () or stopSelf () does not actually stop the service until all clients unbind.

To put it simply, multiple clients can be bound to the same Service. After all bound clients are unbound, the Service will be destory and the stopSelf method is not required, similarly, the onDestory method is not called back. A Client can bind a Service that has already been started. In this way, to stop the service, you must first unbind all bound clients, then call the stopService or stopSelf method.
With the official statement, you can write code with confidence.
For convenience, we define our own Application class-BeApplication to perform relevant operations.
public class BeApplication extends Application implements ServiceConnection {
@Override
public void onCreate() {
    super.onCreate();

    startMainService();
    bindMainService();
}

public void startMainService () {
        Intent it = new Intent (this, MainService.class);
        startService(it);
    }

    public void stopMainService () {
        Intent it = new Intent(this, MainService.class);
        stopService(it);
    }

private void bindMainService () {
        Intent it = new Intent (this, MainService.class);
        this.bindService(it, this, Service.BIND_AUTO_CREATE);
    }

    private void unbindMainService () {
        this.unbindService(this);
    }

@Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service instanceof MainService.ServiceBinder) {
            MainService.ServiceBinder binder = (MainService.ServiceBinder)service;
            mMainService = binder.getService();
            mMainService.registerServiceCallback(mPlayManager);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(this, "onServiceDisconnected name=" + name, Toast.LENGTH_LONG).show();
    }
}



In the onCreate method of this Application class, we first start a Service and then bind it. Note: To make your BeApplication run, you need to define android: name = "package name + class name of our application class" under the <application/> label in the manifest file ".
Now we will write the MainService class for playing music. We also remember to declare this Service in the manfest file.
<pre name="code" class="java">public class MainService extends Service {
public static class ServiceBinder extends Binder {

        private MainService mService = null;

        public ServiceBinder(MainService service) {
            mService = service;
        }

        public MainService getService () {
            return mService;
        }
    }
@Override
    public IBinder onBind(Intent intent) {
        return new ServiceBinder(this);
    }
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return Service.START_STICKY;
        //return super.onStartCommand(intent, flags, startId);
    }
}
Note the onServiceConnected method in BeApplication. In this method, we obtain the IBinder object returned by the onBind method in MainService and use this object, we get this Service for playing music in BeApplication, so it is much easier to interact with the Service.
Maybe you will ask, if you have already obtained the service object, why should we start this service?
Note that the onStartCommend method in MainService returns an int constant. For this constant, the official explanation is as follows:
START_STICKY
If the system kills the service after onStartCommand () returns, recreate the service and call onStartCommand (), but do not redeliver the last intent. instead, the system callonstartcommand () with a null intent, unless there were pending intents to start the service, in which case, those intents are delivered. this is suitable for media players (or similar services) that are not executing commands, but running indefinitely and waiting for a job.

There are also two common constants: START_NOT_STICKY and START_REDELIVER_INTENT, which can be extended here: http://developer.android.com/guide/components/services.html#ExtendingService
The function of this variable is that once the system kills the service, the intent in onStartCommand does not work when the service is restarted. This applies to services that do not execute work in onStartCommand.
Service lifecycle flowchart:



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.