2016-08-22 3 views
1

화면이 꺼져 있어도 음악을 계속 듣고 싶을 때 (사용자가 전화기를 잠근 경우에도 음악을 계속 듣고 싶을 때), 사용자가 홈 버튼을 누르면 일시 중지되고 다시 앱으로 돌아 가면 당신이 onPause() 성명에서 play3.pause을하지 말아야 기본적으로 당신의 목표를 달성하기 위해화면이 꺼질 때 음악 재생 계속

public class prathmeshvara extends AppCompatActivity implements Runnable, View.OnClickListener, SeekBar.OnSeekBarChangeListener{ 
TextView tv25; 
Button b47, b48, but32; 
int count = 0; 
MediaPlayer play3; 
SeekBar seek_bar3; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_prathmeshvara); 
    ActionBar actionBar=getSupportActionBar(); 
    actionBar.setDisplayShowHomeEnabled(true); 
    actionBar.setIcon(R.mipmap.icon); 
    tv25 = (TextView) findViewById(R.id.textView25); 
    tv25.setText(Html.fromHtml(getString(R.string.twentyone))); 
    b47 = (Button) findViewById(R.id.b47); 
    b48 = (Button) findViewById(R.id.b48); 
    seek_bar3 = (SeekBar) findViewById(R.id.seekBar3); 
    seek_bar3.setOnSeekBarChangeListener(this); 
    seek_bar3.setEnabled(false); 
    but32 = (Button) findViewById(R.id.button32); 
    but32.setOnClickListener(this); 
} 

public void run() { 
    int currentPosition = play3.getCurrentPosition(); 
    final int total = play3.getDuration(); 
    while (play3 != null && currentPosition < total) { 
     try { 
      Thread.sleep(1000); 
      currentPosition = play3.getCurrentPosition(); 
     } catch (InterruptedException e) { 
      return; 
     } catch (Exception e) { 
      return; 
     } 
     seek_bar3.setProgress(currentPosition); 
    } 
} 

public void onClick(View v) { 
    if (v.equals(but32)) { 
     if (play3 == null) { 
      play3 = MediaPlayer.create(getApplicationContext(), R.raw.prathameshwara); 
      seek_bar3.setEnabled(true); 
     } 
     if (play3.isPlaying()) { 
      play3.pause(); 
      but32.setBackgroundResource(R.drawable.play); 
     } else { 
      play3.start(); 
      but32.setBackgroundResource(R.drawable.pause); 
      seek_bar3.setMax(play3.getDuration()); 
      new Thread(this).start(); 
     } 
    } 
    play3.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
     @Override 
     public void onCompletion(MediaPlayer mp) { 
      play3.seekTo(0); 
      but32.setBackgroundResource(R.drawable.play); 
     } 
    }); 
} 

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    if (play3!= null) 
    { 
     play3.pause(); 
    } 
} 

@Override 
protected void onResume() 
{ 
    super.onResume(); 
    if ((play3 != null) && (!play3.isPlaying())) { 
     but32.setBackgroundResource(R.drawable.play); 
     but32.setOnClickListener(this); 
    } 
} 
@Override 
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { 
    try { 
     if (play3.isPlaying() || play3 != null) { 
      if (fromUser) 
       play3.seekTo(progress); 
     } else if (play3 == null) { 
      Toast.makeText(getApplicationContext(), "First Play", Toast.LENGTH_SHORT).show(); 
      seek_bar3.setProgress(0); 
     } 
    } catch (Exception e) { 
     Log.e("seek bar", "" + e); 
     seek_bar3.setEnabled(false); 
    } 
} 

@Override 
public void onStartTrackingTouch(SeekBar seekBar) { 

} 

@Override 
public void onStopTrackingTouch(SeekBar seekBar) { 

} 
} 

답변

1

: 여기

내 코드입니다 .... 그가 ... 파일 브라우저를 통해 음악을 재생하는 사용자와 유사한 일시 중지 된 곳에서 계속 :

@Override 
protected void onPause() 
{ 
    super.onPause(); 
    if (play3!= null) 
    { 
     play3.pause(); 
    } 
} 

지금 앱이 일시 중지 상태가되면 재생이 일시 중지됩니다. Btw는 시간을 보내고 AudioFocus 처리를 구현하는 것을 잊지 마십시오.

+0

AudioFocus로 도와주세요. – Devk

0

나는 AudioFocus에 대한 모든 배운 그리고 이러한 소스에서 처리하는 것 :

Media playback the right way (Big Android BBQ 2015)

How to properly handle audio interruptions

Managing Audio Focus

AudioManager

AudioManager.OnAudioFocusChangeListener

그리고하는 부족한 중량을 채우는 것에, 여기 당신은 메모리의 무리를 먹고 그들도 그것을 사용하고자하는 경우에는 다른 애플 리케이션을위한 미디어 코덱을 해제하지 않도록 앱 미디어의 resourses을 청소에 대한 몇 가지 정보를 가지고 :

플레이어 활동에서

Cleaning up MediaPlayer resources

+0

내 기존 코드 및 레졸루션을 일부 변경합니다. 문제를 놓치지 마라. 최근에 코딩을 시작 했으니 까. – Devk

0

Releasing the MediaPlayer, onCreate 전에 :

import android.media.AudioManager; 

...

또한
int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener, 
        AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT); 

      if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED){ 
       // we have audio focus now 

       // Create and setup the {@link MediaPlayer} for the audio resource associated with the current word 
       mMediaPlayer = MediaPlayer.create(YourActivity.this, word.getAudioResourceId()); 

       // Start the audio file 
       mMediaPlayer.start(); 

       // Setup a listener on the media player, so that we can stop and release the 
       // media player once the sound has finished playing. 
       mMediaPlayer.setOnCompletionListener(mCompletionListener); 
      } 

난 당신이 플레이어의 활동이를 추가하는 것이 좋습니다 (그러나 내부 onCreate)가 제대로 미디어 리소스를 해제하고, 그것을 사용하기 위해 정지 버튼을 터치하면 다음 onClick 방법 내부
/** Handles audio focus when playing a sound file */ 
private AudioManager mAudioManager; 

/** 
* This listener gets triggered when the {@link MediaPlayer} has completed 
* playing the audio file. 
*/ 


/** 
* This listener gets triggered whenever the audio focus changes 
* (i.e., we gain or lose audio focus because of another app or device). 
*/ 
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener(){ 
    @Override 
    public void onAudioFocusChange(int focusChange){ 
     if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT || 
       focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) { 
       // The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a 
       // short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that 
       // our app is allowed to continue playing sound but at a lower volume. We'll treat 
       // both cases the same way because our app is playing short sound files. 

       // Pause playback and reset player to the start of the file. That way, we can 
       // play the word from the beginning when we resume playback. 
       mMediaPlayer.pause(); 
       mMediaPlayer.seekTo(0); 
     } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) { 
       // The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback. 
       mMediaPlayer.start(); 
     } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) { 
       // The AUDIOFOCUS_LOSS case means we've lost audio focus and 
       // Stop playback and clean up resources 
       releaseMediaPlayer(); 
     } 
    } 
}; 

다른 경우에는 재생을 중지해야합니다.

/** 
* Clean up the media player by releasing its resources. 
*/ 
private void releaseMediaPlayer() { 
    // If the media player is not null, then it may be currently playing a sound. 
    if (mMediaPlayer != null) { 
     // Regardless of the current state of the media player, release its resources 
     // because we no longer need it. 
     mMediaPlayer.release(); 

     // Set the media player back to null. For our code, we've decided that 
     // setting the media player to null is an easy way to tell that the media player 
     // is not configured to play an audio file at the moment. 
     mMediaPlayer = null; 

     // Regardless of whether or not we were granted audio focus, abandon it. This also 
     // unregisters the AudioFocusChangeListener so we don't get anymore callbacks. 
     mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); 
    } 
}