Delay in pause video when removing headphones

综合技术 2017-11-15

I am playing video and trying to pause it when headset is removed. But unfortunately there is a time delay of about 1-2 sec after which music/video gets stopped. The same piece of code works fine when I use it for a music player but not for a video player. Can anyone help?

Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
// Register headset receiver
    registerReceiver(headsetReceiver,
            new IntentFilter(Intent.ACTION_HEADSET_PLUG));}

// If headset gets unplugged, stop music and service.
private final BroadcastReceiver headsetReceiver = new BroadcastReceiver() {
    private boolean headsetConnected = false;

    @Override
    public void onReceive(Context context, Intent intent) {

        // Log.v("TAG", "ACTION_HEADSET_PLUG Intent received");
        if (intent.hasExtra("state")) {
            if (headsetConnected && intent.getIntExtra("state", 0) == 0) {
                headsetConnected = false;
                headsetSwitch = 0;

            } else if (!headsetConnected
                    && intent.getIntExtra("state", 0) == 1) {
                headsetConnected = true;
                headsetSwitch = 1;

            }

        }

        switch (headsetSwitch) {
            case (0):
                headsetDisconnected();
                break;
            case (1):
                break;
            default:
                break;
        }
    }

};

private void headsetDisconnected() {
    if(videoInterface!=null)
        videoInterface.stopVideo();

}

Fragment :

public class VideoPlayerFragment extends Fragment implements VideoInterface
{
 @Override
 public void onAttach(Activity activity) {
    super.onAttach(activity);
    ((VideoPlayer)getActivity()).videoInterface = this;
}
 @Override
 public void stopVideo() {   // interface method
    if (mediaPlayer != null && mediaPlayer.isPlaying())
       mediaPlayer.pause();
}

You can always rewind the video;

int currTime = mediaplayer.getcurrentposition();
    int newTime = currTime - 3000; // 3k milliseconds
    mediaplayer.seekTo(newTime);
Hello, buddy!

责编内容by:Hello, buddy! (源链)。感谢您的支持!

您可能感兴趣的

Android查缺补漏–BroadcastReceiver的类型与使用... Broadcast 是一种被用于应用内和应用之间传递信息的机制。一个广播可以对应多个接受者。一个完整的广播机制,需要具有以下三个要素: 发送广播的...
ANR 产生原因以及原因分析 ANR:Application Not Responding,即应用无响应 ANR.png 官方给出的产生ANR...
Android组件框架:Android组件管理者ActivityManager... 关于作者 郭孝星,程序员,吉他手,主要从事Android平台基础架构方面的工作,欢迎交流技术方面的问题,可以去我的 Github 提issue或者发邮件至...
BroadCastReceiver总结 广播生命周期 广播执行完onReceive()方法,生命周期就结束了。BroadCastReceiver是运行在UI线程的,所以不能进行耗时操作(超过10秒...
Unable to stop service or activity or BroadcastRec... I have a Service that shows a Float Icon which shows the status of the applicat...