2017-04-18 52 views
0

我被這最後一段代碼困住了。 我想要按下按鈕時播放鬧鐘。 警報在MUSIC_STREAM上播放,因爲它只能通過耳機/聽筒播放,所以沒有其他人受到干擾。如何使用Android(Java)在後臺停止播放所有音樂?

public void playAlarm(){ 
try { 
     Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); 
     mMediaPlayer = new MediaPlayer(); 
     mMediaPlayer.setDataSource(this, alert); 
     final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
     originalVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); 

     audioManager.setMode(AudioManager.MODE_IN_CALL); 
     audioManager.setSpeakerphoneOn(false); 
     audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, alarmVolume, 0); 

     mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
     mMediaPlayer.setLooping(true); 
     mMediaPlayer.prepare(); 
     mMediaPlayer.start(); 
     mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { 
               @Override 
               public void onCompletion(MediaPlayer mp) { 
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, originalVolume, 0); 
               } 
              }); 
    } catch(Exception e) { 
    } 
} 

^這段代碼在警報觸發時運行。奇蹟般有效。播放默認的鬧鈴聲並重復播放。當我殺了應用程序,聲音停止 - 就像我想要的。

public void killApp(){ 
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
    notificationManager.cancelAll(); 
finish(); 

    moveTaskToBack(true); 
    android.os.Process.killProcess(android.os.Process.myPid()); 
    System.exit(1); 
} 

^This works too too。

不工作的部分是這樣的:

private static void sendMediaButton(Context context, int keyCode) { 
    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN, keyCode); 
    Intent intentPause = new Intent(Intent.ACTION_MEDIA_BUTTON); 
    intentPause.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); 
    context.sendOrderedBroadcast(intentPause, null); 

    keyEvent = new KeyEvent(KeyEvent.ACTION_UP, keyCode); 
    intentPause = new Intent(Intent.ACTION_MEDIA_BUTTON); 
    intentPause.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent); 
    context.sendOrderedBroadcast(intentPause, null); 
} 

^它暫停音樂後級或Player.fm(和其他musicplayers),讓我報警的發揮,但它也重新開始歌曲在我的默認音樂應用程序(PowerAmp) - 音量非常低,但我的警報和歌曲都可以忍受。

當我使用Player.fm播放音樂時,播放器也會暫停,警報將播放,但我的默認音樂應用程序會再次播放。

我試着在網絡上搜索,所有這些代碼:

private static void sendMediaButton2(final Context context, int keyCode){ 
    Intent mediaEvent = new Intent(Intent.ACTION_MEDIA_BUTTON); 
    KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY); 
    mediaEvent.putExtra(Intent.EXTRA_KEY_EVENT, event); 
    context.sendBroadcast(mediaEvent); 

    new Timer().schedule(new TimerTask() { 
     @Override 
     public void run() { 
      Intent mediaEvent = new Intent(Intent.ACTION_MEDIA_BUTTON); 
      KeyEvent event = new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_MEDIA_PLAY); 
      mediaEvent.putExtra(Intent.EXTRA_KEY_EVENT, event); 
      context.sendBroadcast(mediaEvent); 
     } 
    }, 100); 
} 

^不工作

public void stopMusicPlaying5(){ 
    AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 
    String SERVICECMD = "com.android.music.musicservicecommand"; 
    String CMDNAME = "command"; 
    String CMDSTOP = "stop"; 

    if(mAudioManager.isMusicActive()) { 
     Intent i = new Intent(SERVICECMD); 
     i.putExtra(CMDNAME , CMDSTOP); 
     MapsActivity.this.sendBroadcast(i); 
    } 
} 

^不工作

public void stopMusicPlaying(){ 
    KeyEvent ke = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE); 
    Intent intent = new Intent(Intent.ACTION_MEDIA_BUTTON); 
    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 

    // construct a PendingIntent for the media button and unregister it 
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON); 
    //PendingIntent pi = PendingIntent.getBroadcast(AppContext.getContext(), 
    //  0/*requestCode, ignored*/, mediaButtonIntent, 0/*flags*/); 
    intent.putExtra(Intent.EXTRA_KEY_EVENT, ke); 
    //sendKeyEvent(pi, AppContext.getContext(), intent); 

    ke = new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_PAUSE); 
    intent.putExtra(Intent.EXTRA_KEY_EVENT, ke); 
    //sendKeyEvent(pi, AppContext.getContext(), intent); 

    //  android.intent.action.MEDIA_BUTTON 

} 

^不工作

public void stopMusicPlaying1(){ 
    long eventtime = SystemClock.uptimeMillis(); 

    Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); 
    KeyEvent downEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_NEXT, 0); 
    downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent); 
    sendOrderedBroadcast(downIntent, null); 
} 

^不工作

public void stopMusicPlaying4(){ 
    AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); 

    if (audioManager != null){ 
     audioManager = (AudioManager)getSystemService(AUDIO_SERVICE); 
     KeyEvent event = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE); 
     audioManager.dispatchMediaKeyEvent(event); 
    } 
} 

public void stopMusicPlaying2(){ 
    long eventtime = SystemClock.uptimeMillis(); 

    Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null); 
    KeyEvent upEvent = new KeyEvent(eventtime, eventtime, KeyEvent.ACTION_UP, KeyEvent.KEYCODE_MEDIA_STOP, 0); 
    upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent); 
    sendOrderedBroadcast(upIntent, null); 
} 

^而且,奇怪的是,沒有工作。

+0

_「當我殺應用」 _你爲什麼這樣做?停止'MediaPlayer'(也許完成當前的Activity)似乎更合適。至於回放問題,通常的方法是暫時爲您的應用程序請求音頻焦點。 – Michael

+0

@邁克爾可能是一個更好的主意。感謝您的輸入。 –

回答

0

使用下面的代碼:

AudioManager.OnAudioFocusChangeListener focusChangeListener = 
      new AudioManager.OnAudioFocusChangeListener() { 
       public void onAudioFocusChange(int focusChange) { 
        AudioManager am = (AudioManager) 
getSystemService(AUDIO_SERVICE); 
        switch (focusChange) { 

         case 
(AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK): 
          // Lower the volume while ducking. 
          player.setVolume(0.2f, 0.2f); 
          break; 
         case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT): 
          player.pause(); 
          break; 

         case (AudioManager.AUDIOFOCUS_LOSS): 
          player.stop(); 
          break; 

         case (AudioManager.AUDIOFOCUS_GAIN): 

          player.setVolume(1f, 1f); 

          break; 
         default: 
          break; 
        } 
       } 
      }; 

    AudioManager am = (AudioManager) getSystemService(AUDIO_SERVICE); 

// Request audio focus for playback 
    int result = am.requestAudioFocus(focusChangeListener, 
// Use the music stream. 
      AudioManager.STREAM_MUSIC, 
// Request permanent focus. 
      AudioManager.AUDIOFOCUS_GAIN); 


    if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { 
     player.setSource(video); 

    } 
+0

工程就像一個魅力!謝謝! –

相關問題