почему приложение падает при приостановке медиаплеера во фрагменте

#java #android

#java #Android

Вопрос:

вот код

 import androidx.fragment.app.Fragment;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.Button;
import android.os.Bundle;
import android.widget.SeekBar;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;

public class fragment1 extends Fragment {

    MediaPlayer mp;
    Button play;
    SeekBar seekBar;
    TextView elapsedTimeLabel;
    TextView remainingTimeLabel;
    int totalTime;

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

        View rootView = inflater.inflate(R.layout.fragment_fragment1, container, false);

        final MediaPlayer mp = new MediaPlayer();
        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mp.setDataSource("https://firebasestorage.googleapis.com");
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            mp.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }

        final Button play = rootView.findViewById(R.id.play);
        elapsedTimeLabel = rootView.findViewById(R.id.elapsedTimeLabel);
        remainingTimeLabel = rootView.findViewById(R.id.remainingTimeLabel);
        totalTime = mp.getDuration();
        mp.seekTo(0);
        seekBar = rootView.findViewById(R.id.seekBar);
        seekBar.setMax(totalTime);
        seekBar.setOnSeekBarChangeListener

                (new SeekBar.OnSeekBarChangeListener() {
                     @Override
                     public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                         if (fromUser) {
                             mp.seekTo(progress);
                             seekBar.setProgress(progress);
                         }
                     }
                     @Override
                     public void onStartTrackingTouch(SeekBar seekBar) {
                     }
                     @Override
                     public void onStopTrackingTouch(SeekBar seekBar) {
                     }
                 }
                );

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mp != null) {
                    try {
                        Message msg = new Message();
                        msg.what = mp.getCurrentPosition();
                        handler.sendMessage(msg);
                        Thread.sleep(1000);
                    } catch (InterruptedException ignored) {
                    }
                }
            }
        }).start();

        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            public void onCompletion(MediaPlayer sound) {

                play.setBackgroundResource(R.drawable.play);
            }
        });

        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mp.isPlaying()) {
                    mp.pause();
                    play.setBackgroundResource(R.drawable.play);

                    if (mp != null) {
                        mp.release();
                    }
                } else {

                    mp.start();
                    play.setBackgroundResource(R.drawable.pause);
                }

            }

        });

        return rootView;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int currentPosition = msg.what;
            seekBar.setProgress(currentPosition);

            String elapsedTime = createTimeLabel(currentPosition);
            elapsedTimeLabel.setText(elapsedTime);

            String remainingTime;
            remainingTime = createTimeLabel(totalTime - currentPosition);
            remainingTimeLabel.setText("-"   remainingTime);
        }
    };

    public String createTimeLabel(int time) {
        String timelabel;
        int min = time / 1000 / 60;
        int sec = time / 1000 % 60;

        timelabel = min   ":";
        if (sec < 10) timelabel  = "0";
        timelabel  = sec;
        return timelabel;

    }


    public void play(View view) {
        if (mp == null) {
            mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    stopPlayer();
                }
            });
        }

        mp.start();
    }

    public void pause(View view) {
        if (mp != null) {
            mp.pause();
        }
    }

    private void stopPlayer() {
        if (mp != null) {
            mp.release();
            mp = null;

        }
    }
}
  

вот logcat

 2020-10-02 10:06:04.763 9225-9225/? I/xample.raamatt: Not late-enabling -Xcheck:jni (already on)

2020-10-02 10:06:04.806 9225-9225/? I/xample.raamatt: Unquickening 12 vdex files!

2020-10-02 10:06:04.807 9225-9225/? W/xample.raamatt: Unexpected CPU variant for X86 using defaults: x86

2020-10-02 10:06:04.976 9225-9225/com.example.raamattu D/NetworkSecurityConfig: No Network Security Config specified, using platform default

2020-10-02 10:06:04.978 9225-9225/com.example.raamattu D/NetworkSecurityConfig: No Network Security Config specified, using platform default

2020-10-02 10:06:05.014 9225-9249/com.example.raamattu D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so

2020-10-02 10:06:05.022 9225-9249/com.example.raamattu D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so

2020-10-02 10:06:05.028 9225-9249/com.example.raamattu D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so

2020-10-02 10:06:05.255 9225-9225/com.example.raamattu W/xample.raamatt: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)

2020-10-02 10:06:05.255 9225-9225/com.example.raamattu W/xample.raamatt: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)

2020-10-02 10:06:05.469 9225-9247/com.example.raamattu D/HostConnection: HostConnection::get() New Host Connection established 0xf3094410, tid 9247

2020-10-02 10:06:05.473 9225-9247/com.example.raamattu D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 

2020-10-02 10:06:05.476 9225-9247/com.example.raamattu W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...

2020-10-02 10:06:05.479 9225-9247/com.example.raamattu D/EGL_emulation: eglCreateContext: 0xf2ea8330: maj 3 min 0 rcv 3

2020-10-02 10:06:05.525 9225-9247/com.example.raamattu D/EGL_emulation: eglMakeCurrent: 0xf2ea8330: ver 3 0 (tinfo 0xf31f4690) (first time)

2020-10-02 10:06:05.558 9225-9247/com.example.raamattu I/Gralloc4: mapper 4.x is not supported

2020-10-02 10:06:05.559 9225-9247/com.example.raamattu D/HostConnection: createUnique: call

2020-10-02 10:06:05.559 9225-9247/com.example.raamattu D/HostConnection: HostConnection::get() New Host Connection established 0xf30933f0, tid 9247

2020-10-02 10:06:05.560 9225-9247/com.example.raamattu D/goldfish-address-space: allocate: Ask for block of size 0x100

2020-10-02 10:06:05.560 9225-9247/com.example.raamattu D/goldfish-address-space: allocate: ioctl allocate returned offset 0x3fc0a8000 size 0x2000

2020-10-02 10:06:05.591 9225-9247/com.example.raamattu D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer ANDROID_EMU_vulkan_ignored_handles ANDROID_EMU_vulkan_free_memory_sync GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 

2020-10-02 10:06:10.546 9225-9225/com.example.raamattu W/MediaPlayer: Use of stream types is deprecated for operations other than volume control

2020-10-02 10:06:10.546 9225-9225/com.example.raamattu W/MediaPlayer: See the documentation of setAudioStreamType() for what to use instead with android.media.AudioAttributes to qualify your playback use case

2020-10-02 10:06:10.549 9225-9225/com.example.raamattu V/MediaHTTPService: MediaHTTPService(android.media.MediaHTTPService@13a9e9e): Cookies: null

2020-10-02 10:06:10.555 9225-9243/com.example.raamattu V/MediaHTTPService: makeHTTPConnection: CookieManager created: java.net.CookieManager@e7ddd7f

2020-10-02 10:06:10.556 9225-9243/com.example.raamattu V/MediaHTTPService: makeHTTPConnection(android.media.MediaHTTPService@13a9e9e): cookieHandler: java.net.CookieManager@e7ddd7f Cookies: null

2020-10-02 10:06:11.761 9225-9225/com.example.raamattu I/Choreographer: Skipped 75 frames!  The application may be doing too much work on its main thread.

2020-10-02 10:06:11.828 9225-9247/com.example.raamattu I/OpenGLRenderer: Davey! duration=1330ms; Flags=0, IntendedVsync=756529359630, Vsync=757779359580, OldestInputEvent=9223372036854775807, NewestInputEvent=0, HandleInputStart=757794169300, AnimationStart=757794219600, PerformTraversalsStart=757794530400, DrawStart=757808726500, SyncQueued=757811526300, SyncStart=757813102200, IssueDrawCommandsStart=757814731200, SwapBuffers=757858684100, FrameCompleted=757861165100, DequeueBufferDuration=693000, QueueBufferDuration=1043000, GpuCompleted=0, 

2020-10-02 10:06:17.219 9225-9225/com.example.raamattu V/MediaPlayer: resetDrmState:  mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false

2020-10-02 10:06:17.219 9225-9225/com.example.raamattu V/MediaPlayer: cleanDrmObj: mDrmObj=null mDrmSessionId=null

2020-10-02 10:06:17.236 9225-9225/com.example.raamattu W/MediaPlayer: mediaplayer went away with unhandled events

2020-10-02 10:06:17.772 9225-9258/com.example.raamattu E/AndroidRuntime: FATAL EXCEPTION: Thread-2
    Process: com.example.raamattu, PID: 9225
    java.lang.IllegalStateException
        at android.media.MediaPlayer.getCurrentPosition(Native Method)
        at com.example.raamattu.fragment1$2.run(fragment1.java:77)
        at java.lang.Thread.run(Thread.java:923)

2020-10-02 10:06:22.894 9225-9241/com.example.raamattu W/System: A resource failed to call release.
  

итак, проблема в том, что приложение вылетает при нажатии на паузу

строка 77 — это msg.what = mp.getCurrentPosition();

я был бы очень признателен, если бы кто-нибудь дал мне пример фрагмента кода, который я должен добавить, чтобы заставить приложение работать.

Комментарии:

1. сбой происходит из-за того, что вы получаете исключение IllegalStateException, пожалуйста, убедитесь, что ваш медиаплеер находится в запущенном состоянии, прежде чем вызывать stop или pause на нем

2. @Jayanth. спасибо за ответ. извините, я ничего не знаю о кодировании. можете ли вы привести мне пример того, что я должен изменить?

3. конечно, пожалуйста, обратитесь к этой ссылке для использования MediaPlayer tutorialspoint.com/android/android_mediaplayer.htm

Ответ №1:

Удалить .release() в

     @Override
    public void onClick(View view) {
        if (mp.isPlaying()) {
            mp.pause();
            play.setBackgroundResource(R.drawable.play);

            //if (mp != null) {
                //mp.release();
            //}
        } else {

            mp.start();
            play.setBackgroundResource(R.drawable.pause);
        }

    }
  

Вы должны .release() проигрывать, когда выполняете всю работу с ним или когда фрагмент / действие уничтожается