按下后退按钮时强制关闭片段

时间:2016-07-08 13:33:28

标签: android android-fragments audio

我的Android应用程序有问题。有一个Custome适配器从我调用一个片段,其中有mediaPlayer播放音频文件。片段启动时,播放音频文件。如果用户按下ActionBar中的后退按钮,则不会出现任何问题,并切换到启动此片段的前一个片段。但是当用户再次按下后退按钮时,会发生错误" MyApp停止工作"。我试图通过断点在我的主要活动的onBackPressed方法上捕获问题,但在调用此方法之前出现错误。

我的自定义适配器中的代码调用音频片段:

    android.support.v4.app.FragmentTransaction fragmentTransaction;
                    FragmentManager fragmentManager = ((AppCompatActivity) context).getSupportFragmentManager();
                    AudioFragment fragment = new AudioFragment();
                    fragment.SoundTitle = currentAV.getFileText();
                    fragment.oneTimeOnly = 0;
                    fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.replace(R.id.fragment_container, fragment);
                    fragmentTransaction.commit();

我的音频代码片段有媒体播放器:

public class AudioFragment extends Fragment {

private Button btnForward, btnPause, btnPlay, btnBackward;
private ImageButton btnStop;
private ImageView iv;
private MediaPlayer mediaPlayer;
private double startTime = 0;
private double finalTime = 0;
private Handler myHandler;
private int forwardTime = 90000;
private int backwardTime = 90000;
private SeekBar seekbar;
private TextView tx1,tx2,tx3, txTitle;

private boolean _isStopped = true;
private int _length = 0;

public static int oneTimeOnly = 0;
public static String SoundTitle = "";

public AudioFragment() {
    // Required empty public constructor
}


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

    View view =  inflater.inflate(R.layout.fragment_audio, container, false);

    btnForward = (Button) view.findViewById(R.id.btnForward);
    btnPause = (Button) view.findViewById(R.id.btnPause);
    btnPlay = (Button)view.findViewById(R.id.btnPlay);
    btnBackward = (Button)view.findViewById(R.id.btnBackward);
    btnStop = (ImageButton)view.findViewById(R.id.btnStop);
    iv=(ImageView)view.findViewById(R.id.imageView);

    txTitle =(TextView)view.findViewById(R.id.textview);
    txTitle.setText(SoundTitle);
    tx1=(TextView)view.findViewById(R.id.textView2);
    tx2=(TextView)view.findViewById(R.id.textView3);
    tx3=(TextView)view.findViewById(R.id.textView4);
    tx3.setText("");

    myHandler = new Handler();
    seekbar=(SeekBar)view.findViewById(R.id.seekBar);

    ((AppCompatActivity)getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    ((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);

    toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getActivity().onBackPressed();
        }
    });


    btnPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Playing sound",Toast.LENGTH_SHORT).show();
            PlaySound();
        }
    });

    btnPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getActivity(), "Pausing sound",Toast.LENGTH_SHORT).show();
            mediaPlayer.pause();
            _length = mediaPlayer.getCurrentPosition();
            btnPause.setEnabled(false);
            btnPlay.setEnabled(true);
        }
    });

    btnForward.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int temp = (int)startTime;

            if((temp+forwardTime)<=finalTime){
                startTime = startTime + forwardTime;
                mediaPlayer.seekTo((int) startTime);
                //Toast.makeText(getActivity(),"You have Jumped forward 5 seconds",Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getActivity(),"Cannot jump forward 60 seconds",Toast.LENGTH_SHORT).show();
            }
        }
    });

    btnBackward.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int temp = (int)startTime;

            if((temp-backwardTime)>0){
                startTime = startTime - backwardTime;
                mediaPlayer.seekTo((int) startTime);
                //Toast.makeText(getActivity(),"You have Jumped backward 5 seconds",Toast.LENGTH_SHORT).show();
            }
            else{
                Toast.makeText(getActivity(),"Cannot jump backward 60 seconds",Toast.LENGTH_SHORT).show();
            }
        }
    });

    btnStop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            btnPause.setEnabled(false);
            btnPlay.setEnabled(true);
            _isStopped = true;
            _length = 0;
            mediaPlayer.stop();
            myHandler.removeCallbacks(UpdateSongTime);
            mediaPlayer.release();
            mediaPlayer=null;
        }
    });

    PlaySound();
    return view;
}


private Runnable UpdateSongTime = new Runnable() {
    public void run() {
        startTime = mediaPlayer.getCurrentPosition();
        tx1.setText(String.format("%d min, %d sec",

                TimeUnit.MILLISECONDS.toMinutes((long) startTime),
                TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                        TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.
                                toMinutes((long) startTime)))
        );
        seekbar.setProgress((int)startTime);
        myHandler.postDelayed(this, 100);
    }
};


private void PlaySound(){
    if(!_isStopped){
        mediaPlayer.seekTo(_length);
        mediaPlayer.start();
        btnPause.setEnabled(true);
        btnPlay.setEnabled(false);
        return;
    }
    String sdpath = Environment.getExternalStorageDirectory().getAbsolutePath();
    String avPath = "";
    avPath = sdpath + Gen.AudioPath;
    _isStopped = false;
    mediaPlayer = MediaPlayer.create(getActivity(), Uri.parse(avPath));
    seekbar.setClickable(false);
    btnPause.setEnabled(false);

    mediaPlayer.start();
    finalTime = mediaPlayer.getDuration();
    startTime = mediaPlayer.getCurrentPosition();

    if (oneTimeOnly == 0) {
        seekbar.setMax((int) finalTime);
        oneTimeOnly = 1;
    }
    tx2.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
            TimeUnit.MILLISECONDS.toSeconds((long) finalTime) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime)))
    );

    tx1.setText(String.format("%d min, %d sec",
            TimeUnit.MILLISECONDS.toMinutes((long) startTime),
            TimeUnit.MILLISECONDS.toSeconds((long) startTime) -
                    TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime)))
    );

    seekbar.setProgress((int)startTime);
    myHandler.postDelayed(UpdateSongTime,100);
    btnPause.setEnabled(true);
    btnPlay.setEnabled(false);
    Gen.IsMediaPlayerRun = true;
}

}

如果有人有解决方案,请帮忙。感谢

编辑:以下是LOGCAT(最后一行)

D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
  Process: com.example.khan.abc, PID: 21144
  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.FragmentActivity.onBackPressed()' on a null object reference
  at com.example.khan.abc.AudioFragment$1.onClick(AudioFragment.java:125)
  at android.view.View.performClick(View.java:4848)
  at android.view.View$PerformClick.run(View.java:20262)
  at android.os.Handler.handleCallback(Handler.java:815)
  at android.os.Handler.dispatchMessage(Handler.java:104)
  at android.os.Looper.loop(Looper.java:194)
  at android.app.ActivityThread.main(ActivityThread.java:5631)
  at java.lang.reflect.Method.invoke(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:372)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)

1 个答案:

答案 0 :(得分:1)

此代码生成空指针...

 toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View v) { 
        getActivity().onBackPressed(); 
    }
 });

添加空指针保护

 toolbar.setNavigationOnClickListener(new View.OnClickListener() { 
     @Override public void onClick(View v) { 
        Activity parent = getActivity();
        if(parent != null)
            parent.onBackPressed(); 
    }
 });

但是,你的代码有点奇怪......

例如:您创建片段并为工具栏设置clickListener。然后,您返回到上一个片段..但是,您的工具栏仍在引用来自已杀死片段的侦听器...

我认为最好的方法是在父活动中处理工具栏......我不确定你是否可以......但我会改变它......

希望这可以提供帮助。