How to resume activity with audio in Android?

大憨熊 提交于 2019-12-06 11:36:18

问题


I have implemented media player. I have only one Activity. When I'm starting the activity, my music starts to play and when I press the back button the music clip is in pause state, and again when I resume my activity, the music resumes properly. But there is error after I try to resume my Application after song got over. The app crashed, and I'm getting exception for IllegalStateException in back-press method( mp.pause();).

Please have a look at below code and suggest if I am doing something wrong.

public class Audio_Activity extends Activity 
{
    private  MediaPlayer mp;
    Button btnStartStop ;

    int length;
    SharedPreferences prefs;
    ImageView imgVw;

    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();
        btnChapter.setEnabled(false);

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

     @Override
        public void onConfigurationChanged(Configuration newConfig) {
            super.onConfigurationChanged(newConfig);

            // Checks the orientation of the screen
            if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
                Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
            } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
                Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            }
        }

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

          SharedPreferences. Editor prefsEdit = prefs.edit();

          int position = mp.getCurrentPosition();
          prefsEdit.putInt("mediaPosition", position);
          prefsEdit.commit();
        }

     @Override
        protected void onResume() 
        {
            super.onResume();
            System.out.println("Activity is Resume !!!");

                  int position = prefs.getInt("mediaPosition", 0);
                  mp.seekTo(position);
        }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) 
    {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) 
        { 
            if(mp!= null)
            {
                f(mp.isPlaying())
                {
                    mp.pause();
                }
            }
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}

Here is my Log Cat

07-09 11:52:01.057: I/System.out(6854): Music is over and Button is enable !!!!!!
07-09 11:52:03.297: D/AndroidRuntime(6854): Shutting down VM
07-09 11:52:03.297: W/dalvikvm(6854): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-09 11:52:03.339: E/AndroidRuntime(6854): FATAL EXCEPTION: main
07-09 11:52:03.339: E/AndroidRuntime(6854): java.lang.IllegalStateException
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.media.MediaPlayer.isPlaying(Native Method)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at com.audio_demo.Audio_Activity.onKeyDown(Audio_Activity.java:203)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.view.KeyEvent.dispatch(KeyEvent.java:2609)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.app.Activity.dispatchKeyEvent(Activity.java:2375)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1847)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3701)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3651)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2818)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.os.Looper.loop(Looper.java:137)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at android.app.ActivityThread.main(ActivityThread.java:5041)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at java.lang.reflect.Method.invokeNative(Native Method)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at java.lang.reflect.Method.invoke(Method.java:511)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-09 11:52:03.339: E/AndroidRuntime(6854):     at dalvik.system.NativeStart.main(Native Method)
07-09 11:52:28.787: I/Process(6854): Sending signal. PID: 6854 SIG: 9

回答1:


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);
            }
        }


来源:https://stackoverflow.com/questions/17545166/how-to-resume-activity-with-audio-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!