0

Я делаю приложение, и в настоящее время я работаю над добавлением фоновой музыки к нему. Я видел много способов сделать это, и я решил сделать это с помощью службы. Моя проблема, однако, наступает, когда я звоню в Службу, из-за того, что я ничего не слышу, музыка не играет! Я сравнил с другими примерами и попробовал почти все, но изменений нет ... Вместо этого я использую IntentService для воспроизведения музыки (чтобы иметь хотя бы что-то), но это не очень хорошо, потому что пример, когда я нажимаю кнопку домой, музыка продолжает играть ...Использование MediaPlayer в классе обслуживания ...?

код класса обслуживания заключается в следующем:

package edu.ub.pis2016.darmas.entrega1; 


    import android.app.Service; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.media.AudioManager; 
    import android.media.MediaPlayer; 
    import android.os.IBinder; 
    import android.widget.Toast; 


    public class Service_1 extends Service { 

     MediaPlayer player; 


     public IBinder onBind(Intent arg0) { 

      return null; 
     } 

     @Override 
     public void onCreate(){ 
      super.onCreate(); 
      player = MediaPlayer.create(this, R.raw.calm); 
      player.setLooping(true); // Set looping 
      player.setVolume(100,100); 
     } 

     @Override 
     public int onStartCommand(Intent intent, int flags, int startId){ 
      player.start(); 

      return 1; 
     } 


     @Override 
     public void onDestroy(){ 
      player.stop(); 
      player.release(); 
      player = null; 
     } 


     public void onStop(){ 
      player.stop(); 
     } 

     public void onPause(){ 

     } 


    } 

и я вызываю службу от одного из моей деятельности, выполнив:

Intent intent = new Intent(this, Service_1.class); 
startService(intent); 

Но не работает ... Ins TEAD, вот мой код класса IntentService:

package edu.ub.pis2016.darmas.entrega1; 

    import android.app.IntentService; 
    import android.content.Context; 
    import android.content.Intent; 
    import android.media.AudioManager; 
    import android.media.MediaPlayer; 
    import android.os.IBinder; 
    import android.view.KeyEvent; 
    import android.widget.Toast; 

    /* 
    * Service_music Class which extends from IntentService class. We do this due to with this latter, 
    * there's no need to implement a thread thanks to it creates by default (a worker thread), 
    * which runs in the background. Also, this class implements from Audiomanager, in order to 
    * control the different situations in where the music can be found through the phone. 
    * 
    */ 
    public class Service_music extends IntentService implements AudioManager.OnAudioFocusChangeListener { 

     MediaPlayer mp; 
     AudioManager audioManager; 
     boolean end = false; 



     /* 
     * ------------------------------------------------ 
     * -   Class Itself Methods    - 
     * ------------------------------------------------ 
     */ 

     // Constructor class, required! We create here our worker thread 
     public Service_music() { 
      super("Service_music_thread"); 
     } 


     public IBinder onBind(Intent arg0) { 

      return null; 
     } 

     @Override 
     protected void onHandleIntent(Intent intent) { 

      lets_play_music(); 
      while (end != true){} 
     } 


     @Override 
     public void onDestroy(){ 
      super.onDestroy(); // It's mandatory to call the super() methods when extending from IntentService 
      if (this.mp != null) releaseMediaPlayer(); 

     } 


     /* 
     * ------------------------------------------------ 
     * -    Initialize Methods    - 
     * ------------------------------------------------ 
     */ 

     // Method to initialize the media player 
     private void initializeMediaPlayer(){ 
      //this.mp = MediaPlayer.create(this, R.raw.calm); 
      this.mp = MediaPlayer.create(this, R.raw.barefootandbruisdjamestownstory); 
      this.mp.setLooping(true); 
      this.mp.start(); 
     } 


     private void initializeAudioManager(){ 
      this.audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
      int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, 
      AudioManager.AUDIOFOCUS_GAIN); 

      if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { 
       // could not get audio focus. 
       Toast.makeText(getApplicationContext(), "Ha habido un error al iniciar la musica :(", Toast.LENGTH_SHORT).show(); 
      } 
     } 

     /* 
     * ------------------------------------------------ 
     * -    Auxiliar Methods    - 
     * ------------------------------------------------ 
     */ 

     // This method will carry the task of playing the music, but notice this is only for local media! 
     private void lets_play_music(){ 
      initializeAudioManager(); 
      initializeMediaPlayer(); 
      //initializeAudioManager(); 
      //this.mp.start(); 
     } 


     // Method to release all resources taken by the mp object 
     private void releaseMediaPlayer(){ 
      this.mp.stop(); 
      this.mp.release(); 
      this.mp = null; 
     } 


     /* 
     * ------------------------------------------------ 
     * -   Audio Manager Methods    - 
     * ------------------------------------------------ 
     */ 

     public void onAudioFocusChange(int focusChange) { 
      // Do something based on focus change... 
      switch (focusChange){ 

       // Case if we have gained the focus to play! 
       case AudioManager.AUDIOFOCUS_GAIN: 
        if (this.mp == null) initializeMediaPlayer(); // If we had to release the mp by any reason, we re-initialize it! 
        else if(!this.mp.isPlaying()) { 
         this.mp.setLooping(true); // In theory, it should play looping through infinitely 
         this.mp.start(); // If it's not currently playing, starts! 
        } 
        this.mp.setVolume(1.0f, 1.0f); // We set the volume! 
        break; 

       // Case if we have completely (or almost) lost the focus 
       case AudioManager.AUDIOFOCUS_LOSS: 
        if (this.mp.isPlaying()) this.mp.stop(); // If it's currently playing, we have to stop it first 
        end = true; 
        releaseMediaPlayer(); // We release the resources 
        break; 

       // Case if we have lost the focus for a short period of time 
       case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: 
        if (this.mp.isPlaying()) this.mp.pause(); // If it's currently playing, we just pause it! 
        break; 

       // Case if we have lost the focus but for a tiny piece of time, so we're allowed to continue performing the music but in a quiet state! 
       case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: 
        if (this.mp.isPlaying()) this.mp.setVolume(0.3f, 0.3f); // If it's currently playing, we just set the volume to a quiet level! 
        break; 
      } 
     } 


    } 

Этот последний работает, но не «AudioManager», и при нажатии «кнопки домой» музыка продолжает играть ...

Если кто-то может помочь мне или сообщить мне, где ошибка, или что я делаю плохо, чтобы исправить это, я был бы чрезвычайно благодарен, потому что я с ума схожу с этим ...

ответ

1

Два догадки (должные к отсутствию полного кода):

Ваш манифест не содержит услуги, поэтому он не получите намерение R.raw.value не существует

+0

Да, вы правы, я забыл эту деталь в своем манифесте, но в любом случае класс Service работает даже хуже, чем с помощью IntentService! Я нажимаю кнопку «Домой» и продолжаю играть, даже если я выключу приложение, он все еще играет музыку! :(@ Kenneth Hippolite – wj127

+0

Да ... по определению служба должна продолжать работать, даже если основная сведена к минимуму (таким образом, часы никогда не останавливаются при минимизации). Вам необходимо передать намерение от пользовательского интерфейса к сервису прекратить воспроизведение в соответствующее время (например, потеря фокуса). –

Смежные вопросы