如何从片段返回活动时按设备后退按钮使媒体播放器停止 [英] How to make media player stop when pressing device back button from a fragment back to activity

查看:60
本文介绍了如何从片段返回活动时按设备后退按钮使媒体播放器停止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是,当我按下设备后退按钮时,媒体播放器会继续播放.如何在按下设备后退按钮时完全破坏片段和媒体播放器以及其中的所有内容,以使其在屏幕上不可见?

My problem is that media player keeps playing when i press device back button. How to completely destroy the fragment and the media player and everything in it when pressing device back button so that it is not visible on the screen?

我是编程的新手,因此欢迎您提出所有有关改进代码的建议和意见.谢谢

I'm new to programming so all advice and comments on how to improve the code are welcome. Thank you

活动:

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button button1;
    Button button2;
    Button button3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        button1 = findViewById(R.id.button1);
        button2 = findViewById(R.id.button2);
        button3 = findViewById(R.id.button3);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm= getSupportFragmentManager();
                fragment1 fragment = new fragment1();
                fm.beginTransaction()
                        .replace(R.id.container,fragment)
                        .addToBackStack(null)
                        .commit();
            }
        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm= getSupportFragmentManager();
                fragment2 fragment= new fragment2();
                fm.beginTransaction()
                        .replace(R.id.container,fragment)
                        .addToBackStack(null)
                        .commit();
            }
        });

        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                FragmentManager fm= getSupportFragmentManager();
                fragment3 fragment= new fragment3();
                fm.beginTransaction()
                        .replace(R.id.container,fragment)
                        .addToBackStack(null)
                        .commit();
            }
        });
    }
}

片段:

import androidx.fragment.app.Fragment;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Bundle;
import android.widget.SeekBar;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;

public class fragment1 extends Fragment {

    MediaPlayer mp;
    Button play;
    SeekBar seekBar;
    TextView elapsedTimeLabel;
    TextView remainingTimeLabel;
    int totalTime;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_fragment1, container, false);

        final MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource("https://firebasestorage.googleapis.com...");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        final Button play = rootView.findViewById(R.id.play);
        elapsedTimeLabel = rootView.findViewById(R.id.elapsedTimeLabel);
        remainingTimeLabel = rootView.findViewById(R.id.remainingTimeLabel);
        totalTime = mp.getDuration();
        mp.seekTo(0);
        seekBar = rootView.findViewById(R.id.seekBar);
        seekBar.setMax(totalTime);
        seekBar.setOnSeekBarChangeListener

                (new SeekBar.OnSeekBarChangeListener() {
                     @Override
                     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                         if (fromUser) {
                             mp.seekTo(progress);
                             seekBar.setProgress(progress);
                         }
                     }
                     @Override
                     public void onStartTrackingTouch(SeekBar seekBar) {
                     }
                     @Override
                     public void onStopTrackingTouch(SeekBar seekBar) {
                     }
                 }
                );

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mp != null) {
                    try {
                        Message msg = new Message();
                        msg.what = mp.getCurrentPosition();
                        handler.sendMessage(msg);
                        Thread.sleep(1000);
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }).start();

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            public void onCompletion(MediaPlayer sound) {

                play.setBackgroundResource(R.drawable.play);
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mp.isPlaying()) {
                    mp.pause();
                    play.setBackgroundResource(R.drawable.play);

                } else {

                    mp.start();
                    play.setBackgroundResource(R.drawable.pause);
                }

            }

        });

        return rootView;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int currentPosition = msg.what;
            seekBar.setProgress(currentPosition);

            String elapsedTime = createTimeLabel(currentPosition);
            elapsedTimeLabel.setText(elapsedTime);

            String remainingTime;
            remainingTime = createTimeLabel(totalTime - currentPosition);
            remainingTimeLabel.setText("-" + remainingTime);
        }
    };

    public String createTimeLabel(int time) {
        String timelabel;
        int min = time / 1000 / 60;
        int sec = time / 1000 % 60;

        timelabel = min + ":";
        if (sec < 10) timelabel += "0";
        timelabel += sec;
        return timelabel;

    }


    public void play(View view) {
        if (mp == null) {
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlayer();
                }
            });
        }

        mp.start();
    }

    public void pause(View view) {
        if (mp != null) {
            mp.pause();
        }
    }

    private void stopPlayer() {
        if (mp != null) {
            mp.release();
            mp = null;

        }
    }
}

我尝试了提供的解决方案,但是片段中的mediaplayer却不被破坏.当我返回片段时,其中的搜索栏被重置,但音频文件仍在播放.当我再次按播放"时,它将开始在上一个播放文件的顶部再次播放,以便同时播放2个文件

I tried the provided solutions but somehow the mediaplayer in the fragment doesnt get destroyed. When I go back to the fragment the seekbar in it is reset but the audio file is still playing. When I press play again it starts to play again on top of the previous one so that theres 2 files playing on the same time

推荐答案

每个片段都有一个 onDestroy()回调,用于将片段从后堆栈中弹出并销毁.您可以从该方法调用 stopPlayer().

Each Fragment has an onDestroy() callback for when the fragment is popped off the back stack and destroyed. You can call your stopPlayer() from that method.

@Override
public void onDestroy() {
    super.onDestroy();
    stopPlayer();
}

这篇关于如何从片段返回活动时按设备后退按钮使媒体播放器停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆