How Android determines if the current phone is playing music and gets information about the music that is playing

Source: Internet
Author: User

I want to implement the following scenario to determine if the music is playing on the current Android phone, and if so, through a specific gesture,

Or click on a button to share the music I'm listening to now. The first step is to determine whether there is currently music playing. At first I thought a little bit complicated, thought to go into the framework or the lower layer to tamper with, find a bit of information, found that Audiomanager external exposed interface. [Java]  /** Checks whether any music is active. */ ismusicactive ()   Through this interface, you can tell if the current system has music playing.   There is a problem, if I want to be in the beginning of the music has been played, I know this event, in order to carry out special processing. Further look at the source code of Audiomanager, found that there are the following methods:[java]    /**      *  request Audio focus.& nbsp;     *  send a request to obtain the audio focus      *   @param l the Li Stener to be notified of audio focus changes      *   @param streamtype the main audio stream type Affected by the focus request      *   @param durationhint use {@link #AUDIOFOCUS_GAIN_TRANSIENT} To indicate this focus request      *      is temporary, and focus would be abandonned Shortly. Examples of Transient requests are      *      for the playback of driving directIons, or notifications sounds.      *      use {@link #AUDIOFOCUS_GAIN_TRANSIENT_MAY_ DUCK} to indicate also it's OK for      *      the previous focus owner to keep PL Aying If it ducks it audio output.      *      use {@link #AUDIOFOCUS_GAIN} for a FOCU s request of unknown duration such      *      as the playback of a song or a VIDEO.&NB sp;     *   @return {@link #AUDIOFOCUS_REQUEST_FAILED} or {@link #AUDIOFOCUS_REQUEST_GRANTED}       */     public int requestaudiofocus (onaudiofocuschangelistener l, int streamtype, int Durationhint)    literally: request audio focus, then look at the return value of this function:[java]    /**      * A failed Focus Change request.      */     public static final int audiofocus_request_failed = 0;      &nbsp  /**      * A Successful focus change request.      */     p ublic static final int audiofocus_request_granted = 1;    This function may be helpful for me to check out Google's official help: http://developer.android.com/training/managing-audio/ Audio-focus.htmlmanaging Audio Focuswith Multiple apps potentially playing Audio it ' s important to think about how they sh Ould Interact. To avoid every music app playing @ the same time, Android uses audio focus to moderate audio playback-only apps The audio focus should play audio. Before your app starts playing audio it should request-and receive-the audio focus.  likewise, it should know how to listen for a loss of audio focus and respond appropriately if that happens.  Jane Single translation: Managing audio focus multiple apps are playing the audio, so it's important to consider how the app interacts with each other. To prevent each music app from playing simultaneously, Android uses the audio focus to coordinate the playback of the audio----only the app that gets to the audio focus can play the audio. Before your app starts playing audio, it should request-and receive the audio focus. Similarly, it should know how to respond reasonably when the supervisor hears the loss of the audio focus.   Along this road should be right, write the following test code to verify. This is primarily a service implementation, and you also need to implement a Activity to start service, end Service:[java]  package com.example.servicetest;    import Android.app.Service;  import Android.content.Context;  import android.content.Intent;  import Android.media.AudioManager;  import Android.media.AudioManager.OnAudioFocusChangeListener;  import Android.media.MediaPlayer;  import Android.os.IBinder;  import Android.util.Log;  import Android.widget.Toast;    public class Mainservice extends Service  {     private static final String TAG = " Mainservice ";            private MediaPlayer player;            private Audiomanager mAm;            private Myonaudiofocuschangelistener Mlistener;              @Override      public void onCreate ()  & nbsp   {         LOG.I (TAG, "OncreaTE ");                    player = Mediaplayer.create (this, r.raw.test);  //Create a new raw directory under the Res directory and copy a Test.mp3 file to this directory.          player.setlooping (false);                    mAm = (Audiomanager) getapplicationcontext (). GE Tsystemservice (Context.audio_service);          Mlistener = new Myonaudiofocuschangelistener ();                   @Override      public Ibin Der Onbind (Intent Intent)      {         return null;     } &nbsp ;            @Override      public void OnStart (Intent Intent, int Startid)      {         Toast.maketext (this, "My Service Start", Toast.length_lo NG). Show ();        &nbsp LOG.I (TAG, "OnStart");                   //Request audio focus for playback          int result = Mam.requestaudiofocus (Mlistener,                  Audiomanager.stream_music,                  AUDIOMANAGER.AUDIOFOCUS_ GAIN);                    if (result = = Audiomanager.audiofocus_request_g ranted)          {             LOG.I (TAG, "Requestaudiofocus Successfully. ");                           //Start playback.              Player.start ();         }          Else          { &nbsp ;         &NBsp LOG.E (TAG, "Requestaudiofocus failed.");         }     }              @Overr IDE      public void OnDestroy ()      {         Toast.maketext (thi S, "My Service stoped", Toast.length_long). Show ();          LOG.I (TAG, "OnDestroy");          player.stop ();                    Mam.abandonaudiofocus (Mlistener);                   Private class Myonaudiofocuschangelistener implements              Onaudiofocuschangelistener      {         @Override          public void ONAUDIOFOC Uschange (int focuschange)          {             LoG.I (TAG, "focuschange=" + focuschange);         }     }  }    and everyday sounds combined to test, first open every day to play music, and then start the service, found every day Listen to the automatic pause, and then stop the service, every day sounds and began to play. In turn, I start this service first, then play, pause every day, "LOG.I (TAG," focuschange= "+ focuschange);" This does have an output log.   Mainstream music player, all follow this rule, so by using this mechanism of Android, we can monitor music playback.   One more question, how do you know what music information is currently playing? Two ideas: 1, through the background to automatically intercept the output of the audio stream, through the server to listen to the song, 2, through the systemui to intercept the mainstream music player notification;  1th idea, from the principle is feasible, but the realization of the difficulty is relatively large, and heavily dependent on the network , or first to analyze the 2nd idea. First find the mainstream Android music player to do a simple test, such as: Every day, QQ music, cool dog music, cool music, Baidu Music, in the process, will send a notification message to the status bar, which already contains song information. Then I just need to do a special intercept and match the package name to get the music playing.   Specific ideas are as follows: 1, to achieve a service, this service in Android phone startup, automatically run, through the Audiomanager.requestaudiofocus () to get audio focus, but nothing to do, Get a notification message only for other music players to start running, 2, modify the Systemui, when the mainstream music player notification to the status bar, get music information from, 3, Step 1 listener can be integrated into Systemui, So when the music focus by other music player snatched, and then combined with the recently received notification notification, so more accurate;

How Android determines if the current phone is playing music and gets information about the music that is playing

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.