在Android中,可以通过监听屏幕关闭广播和音频焦点来实现在视频播放期间关闭电源时暂停视频播放的功能。代码示例如下:
//在Activity中注册屏幕关闭广播接收器 private BroadcastReceiver screenOffReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) { //暂停视频播放 //视频暂停的代码 } } }; //在onResume()方法中注册广播接收器 @Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(screenOffReceiver, filter); }
//在onPause()方法中注销广播接收器 @Override protected void onPause() { super.onPause(); unregisterReceiver(screenOffReceiver); }
//获取音频焦点 private AudioManager.OnAudioFocusChangeListener audioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { @Override public void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: case AudioManager.AUDIOFOCUS_LOSS: //暂停视频播放 //视频暂停的代码 break; } } };
//在播放视频前请求音频焦点 private void requestAudioFocus() { AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); int result = audioManager.requestAudioFocus(audioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); if (result != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { //请求音频焦点失败的代码 } }
//在停止播放视频时释放音频焦点 private void releaseAudioFocus() { AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); audioManager.abandonAudioFocus(audioFocusChangeListener); }