我开发了一款Android应用,用户可以通过单击某个片段中的按钮来播放声音。但是,当您退出此片段或关闭应用程序时,它会继续播放。如果退出片段或关闭应用程序,如何停止它?
这就是我播放声音的方式:
public class PageFragment_Bon extends Fragment implements View.OnClickListener{
public static final String ARG_PAGE = "ARG_PAGE";
private int mPage;
private Button start, stop, replay;
private MediaPlayer mediaPlayer;
int [] filer = new int[18];
public static PageFragment_Bon newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
PageFragment_Bon fragment = new PageFragment_Bon();
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_boenner, container, false);
start = (Button) view.findViewById(R.id.start);
start.setOnClickListener(this);
stop = (Button) view.findViewById(R.id.stop);
stop.setOnClickListener(this);
replay = (Button) view.findViewById(R.id.replay);
replay.setOnClickListener(this);
if(filer[mPage] != 0){
start.setVisibility(View.VISIBLE);
stop.setVisibility(View.VISIBLE);
replay.setVisibility(View.VISIBLE);
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), filer[mPage]);
}
@Override
public void onClick(View v) {
if(v == start){
mediaPlayer.start();
}
else if(v == stop){
mediaPlayer.pause();
}
else if(v == replay){
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}
}
答案 0 :(得分:1)
H123,你需要在Fragment中处理onPause()和onResume()事件。
OnPause:
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(mediaplayer != null)
{
mediaplayer.pause();
media_length = mediaplayer.getCurrentPosition();
}
}
OnResume:
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(mediaplayer != null)
{
mediaplayer.seekTo(media_length);
mediaplayer.start();
}
}
更改您的onClick方法,如下所示
@Override
public void onClick(View v) {
if(mediaPlayer == null)
mediaPlayer = MediaPlayer.create(getActivity().getBaseContext(), filer[mPage]);//add this line
if(v == start){
mediaPlayer.start();
}
else if(v == stop){
mediaPlayer.pause();
}
else if(v == replay){
mediaPlayer.seekTo(0);
mediaPlayer.start();
}
}