How to resume activity with audio in Android?

无人久伴 提交于 2019-12-04 15:20:33

As I Understand the problem is about mp.seekTo(posiotion) in onResume() or mp.getCurrentPosition in onPause() method. That exception can because of not initializing the media player. According to the listener when the song finished you make your player stop and released and in onResume on line mp.seekTo(position) caused that exception. Remove mp.release() line in OnCompletion() method and in onResume and onpPause methods. There's another thing you need to do. use a boolean value in your code to understand whether your mediaplayer finished playing or not. Change your onCreat like below:

public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.audio);
        init();
        imgVw.setImageResource(R.raw.teddy_two);

        prefs = PreferenceManager.getDefaultSharedPreferences(this);

        mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
        Log.e("Song is playing","in  Mediya Player ");
        Log.e("Current ","Position -> " + length);
        mp.setLooping(false);
        mp.start();
        prefsEdit.putInt("mediaplaying", true);
        prefsEdit.commit();
        btnChapter.setEnabled(false);

    mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() 
    {
        @Override
        public void onCompletion(MediaPlayer mp) 
        {
            // TODO Auto-generated method stub
            mp.stop();
            prefsEdit.putInt("mediaplaying", false);
            prefsEdit.commit();
            btnChapter.setEnabled(true);
            System.out.println("Music is over and Button is enable !!!!!!");
        }
    });

     @Override
     public void onPause()
     {
          super.onStop();

          SharedPreferences. Editor prefsEdit = prefs.edit();
          boolean isPlaying=prefs.getBoolean("mediaplaying",false);
          if(isPlaying){
              int position = mp.getCurrentPosition();
              prefsEdit.putInt("mediaPosition", position);
              prefsEdit.commit();
          }
        }

     @Override
        protected void onResume() 
        {
            super.onResume();
            System.out.println("Activity is Resume !!!");
            boolean isPlaying=prefs.getBoolean("mediaplaying",false);
            if(isPlaying){
                int position = prefs.getInt("mediaPosition", 0);
                mp.seekTo(position);
            }
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!