我有一个fragment
,其中我使用了 MediaPlayer 和 MediaController 。两者都很好。问题是,当我按后退键时,媒体控制器变为隐藏,但 MediaPlayer 继续播放。如果我再次按下后退按钮,则会调用位于onBackPressed
容器fragment
中的activity
方法。虽然onBackPressed
正在将fragment
更改为上一个,但 Mediaplayer 仍在运行。
我希望知道如何以某种方式制作东西,以便按下前一个片段,同时隐藏媒体控制器,同时停止播放媒体播放器。
我在这里给出了代码。
package com.codetrio.alquran;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
import com.codetrio.alquran.com.codetrio.alquran.util.ChapterDetailAdapter;
import com.codetrio.alquran.db.ChapterDataSource;
import com.codetrio.alquran.model.Chapter;
import com.codetrio.alquran.model.Verse;
import com.codetrio.alquran.db.VerseDataSource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link ChapterDetailsFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link ChapterDetailsFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class ChapterDetailsFragment extends Fragment implements MediaPlayer.OnPreparedListener, MediaController.MediaPlayerControl {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private int pageCount = 0, startFrom = 0, endTo = 4, chapterId, banglaChapterId;
private OnFragmentInteractionListener mListener;
ListView lvChapterDetails;
ChapterDetailAdapter chapterDetailAdapter;
Button btnPrevious, btnNext;
Chapter chapter, banglaChapter;
List<Verse> verses = new ArrayList<Verse>();
List<Verse> banglaVerses = new ArrayList<Verse>();
List<Verse> versesPortion = new ArrayList<Verse>();
List<Verse> banglaVersesPortion = new ArrayList<Verse>();
MediaPlayer mediaPlayer;
MediaController mediaController;
private Handler handler = new Handler();
View tempFragView, increaseFont, decreaseFont;
LinearLayout linearLayout;
float fontSize = 14;
public ChapterDetailsFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment ChapterDetailsFragment.
*/
// TODO: Rename and change types and number of parameters
public static ChapterDetailsFragment newInstance(String param1, String param2) {
ChapterDetailsFragment fragment = new ChapterDetailsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View fragView = inflater.inflate(R.layout.fragment_chapter_details, container, false);
tempFragView = fragView;
btnPrevious = (Button) fragView.findViewById(R.id.btnPrev);
btnNext = (Button) fragView.findViewById(R.id.btnNext);
linearLayout = fragView.findViewById(R.id.forMediaController);
increaseFont = getActivity().findViewById(R.id.btnIncreaseFont);
decreaseFont = getActivity().findViewById(R.id.btnDecreaseFont);
increaseFont.setVisibility(View.VISIBLE);
decreaseFont.setVisibility(View.VISIBLE);
Bundle bundle = getArguments();//.getString("GO_TO_LAST_READ");
if( bundle != null && bundle.containsKey("GO_TO_LAST_READ") && bundle.getString("GO_TO_LAST_READ").equals("true")){
SharedPreferences sharedPref = getActivity().getSharedPreferences(
getString(R.string.shared_pref_name), Context.MODE_PRIVATE);
chapterId = sharedPref.getInt("chapter_id", -1);
pageCount = sharedPref.getInt("page_count", -1);
if(chapterId == -1){
Toast.makeText(getContext(), "No last read condition found. Please read a chapter first", Toast.LENGTH_LONG).show();
btnPrevious.setEnabled(false);
btnNext.setEnabled(false);
}
if(pageCount > -1){
startFrom = (pageCount-1)*4 + 4;
endTo = startFrom + 4;
}
}else{
chapterId = Integer.parseInt(getArguments().getString("chapter_id"));
banglaChapterId = Integer.parseInt(getArguments().getString("bangla_chapter_id"));
}
ChapterDataSource chapterDataSource = new ChapterDataSource(getActivity());
chapterDataSource.open();
banglaChapter = chapterDataSource.getChapterById(banglaChapterId, 0);
chapter = chapterDataSource.getChapterById(chapterId, 1);
chapterDataSource.close();
getActivity().setTitle(banglaChapter.getChapterName());
VerseDataSource verseDataSource = new VerseDataSource(getActivity());
verseDataSource.open();
verses = verseDataSource.getVersesByChapter( (chapterId), 1);
banglaVerses = verseDataSource.getVersesByChapter( (chapterId), 0);
verseDataSource.close();
for(int i=startFrom; i<endTo; i++){
if(i<verses.size()) {
Verse verse = verses.get(i);
versesPortion.add(verse);
Verse bangla = banglaVerses.get(i);
banglaVersesPortion.add(bangla);
}
}
chapterDetailAdapter = new ChapterDetailAdapter((ArrayList<Verse>) versesPortion, (ArrayList<Verse>) banglaVersesPortion, getContext(), fontSize);
lvChapterDetails = (ListView) fragView.findViewById(R.id.lvDetails);
lvChapterDetails.setAdapter(chapterDetailAdapter);
File file = new File("/data/data/com.codetrio.alquran/"+Integer.toString(chapter.getId())+".mp3");
if(file.exists()){
playAudio(file);
}else{
Log.i("NOOOO", "file not found");
}
increaseFont.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fontSize += 2;
chapterDetailAdapter = new ChapterDetailAdapter((ArrayList<Verse>) versesPortion, (ArrayList<Verse>) banglaVersesPortion, getContext(), fontSize);
lvChapterDetails.setAdapter(chapterDetailAdapter);
}
});
decreaseFont.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
fontSize -= 2;
chapterDetailAdapter = new ChapterDetailAdapter((ArrayList<Verse>) versesPortion, (ArrayList<Verse>) banglaVersesPortion, getContext(), fontSize);
lvChapterDetails.setAdapter(chapterDetailAdapter);
}
});
if(pageCount<1) { //for the first page previous button should be disabled
btnPrevious.setEnabled(false);
}
btnPrevious.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
pageCount--;
updateListView();
updateLastRead(chapterId, pageCount);
btnNext.setEnabled(true);
if(pageCount==0){
btnPrevious.setEnabled(false);
}
}
});
btnNext.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
pageCount++;
updateListView();
updateLastRead(chapterId, pageCount);
btnPrevious.setEnabled(true);
}
});
updateLastRead(chapterId, pageCount);
return fragView;
}
/**
*
*/
public void updateListView(){
startFrom = (pageCount-1)*4 + 4;
endTo = startFrom + 4;
if(startFrom < verses.size()) {
chapterDetailAdapter.clear();
versesPortion.clear();
banglaVersesPortion.clear();
for (int i = startFrom; i < endTo; i++) {
if (i < verses.size()) {
Verse verse = verses.get(i);
versesPortion.add(verse);
Verse bangla = banglaVerses.get(i);
banglaVersesPortion.add(bangla);
}else{
btnNext.setEnabled(false);
btnPrevious.setEnabled(true);
}
}
chapterDetailAdapter = new ChapterDetailAdapter((ArrayList<Verse>) versesPortion, (ArrayList<Verse>) banglaVersesPortion, getContext(), fontSize);
lvChapterDetails.setAdapter(chapterDetailAdapter);
}else{
btnNext.setEnabled(false);
btnPrevious.setEnabled(true);
}
}
private void playAudio(File file){
if(mediaPlayer != null && mediaPlayer.isPlaying()){
mediaPlayer.stop();
mediaController.hide();
}
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(this.getActivity(), Uri.fromFile(file));
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this.getActivity());
mediaPlayer.start();
}
/**
* Keeping the last read in shared preferences
* @param chapterId
* @param pageCount
*/
public void updateLastRead(int chapterId, int pageCount){
SharedPreferences sharefPref = getActivity().getSharedPreferences(getString(R.string.shared_pref_name), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharefPref.edit();
editor.putInt("chapter_id", chapterId);
editor.putInt("page_count", pageCount);
editor.commit();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
try{
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(linearLayout);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show(0);
}
});
}catch (Exception e){
}
}
@Override
public void start() {
mediaPlayer.start();
}
@Override
public void pause() {
mediaPlayer.pause();
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
@Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getAudioSessionId() {
return 0;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
public void stopMediaPlayer(){
mediaPlayer.stop();
mediaPlayer = null;
}
}