Closing MediaPlayer properly

2019-05-19 06:45发布

问题:

I've got a MediaPlayer activity that I thought I was finished with until I noticed the verbose LogCat output and saw this constantly repeating.

01-17 17:03:50.466: D/StatusBarPolicy(209): iconIndex=1
01-17 17:03:50.476: V/StatusBarPolicy(209): cdmaLevel:1;max:4
01-17 17:03:50.476: D/StatusBarPolicy(209): iconLevel:1
01-17 17:03:50.476: D/StatusBarService(209): updateIcon slot=phone_signal index=20 viewIndex=14 old=StatusBarIcon(pkg=com.android.systemui id=0x7f020007 level=0 visible=true num=0 ) icon=StatusBarIcon(pkg=com.android.systemui id=0x7f020008 level=0 visible=true num=0 )
01-17 17:03:50.597: V/MediaPlayer(16768): getCurrentPosition
01-17 17:03:50.597: V/MediaPlayerService(82): getCurrentPosition
01-17 17:03:50.597: V/MediaPlayerService(82): [261] getCurrentPosition = 277943
01-17 17:03:50.597: V/MediaPlayerService(82): [261] isPlaying: 0
01-17 17:03:50.597: V/MediaPlayer(16768): isPlaying: 0
01-17 17:03:50.597: V/MediaPlayerService(82): [261] isPlaying: 0
01-17 17:03:50.597: V/MediaPlayer(16768): isPlaying: 0
01-17 17:03:50.847: V/MediaPlayer(16768): getCurrentPosition
01-17 17:03:50.847: V/MediaPlayerService(82): getCurrentPosition
01-17 17:03:50.847: V/MediaPlayerService(82): [261] getCurrentPosition = 277943'

This makes me think I'm not closing my activity properly. The code I'm using for that is

cancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            new AlertDialog.Builder( CastrRecorder.this )
            .setTitle( "Close" )
            .setMessage( "Any unsaved changes will be lost. Continue?" )
            .setPositiveButton( "Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d( "AlertDialog", "Positive" );
                    mPlayer.stop();
                    mPlayer.release();
                    Intent baseIntent = new Intent(Recorder.this, Activity.class);
                    Recorder.this.startActivity(baseIntent);
                }
            })
            .setNegativeButton( "No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.d( "AlertDialog", "Negative" );
                }
            } )
            .show();
        }
    });

The previous code keeps repeating even after the user closes the app completely. I can't help but think that would be bad. What can I do to prevent this?

回答1:

Not sure if this is critical, but I call mPlayer.reset() in between stop() and release() (and I don't see this problem). Are you absolutely sure it's your app that's generating these log entries?

Also, it's important that your media player calls are not run on the UI thread as they can cause ANRs. Also, run them all on the same background thread so that media player calls get serialized, since the MediaPlayer is not thread safe.