简体   繁体   中英

ListView item onClickListener and garbage collector

I have a ListView and an ArrayAdapter. In method getView I create button on each list element. Here is my code for the method onClick

public void onClick(View view) {
    mediaPlayer = MediaPlayer.create(context, audioResourceId);
    mediaPlayer.start();
    button.setBackgroundResource(R.drawable.ic_mic_pressed);
    mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mp) {
            mp.release();
            button.setBackgroundResource(R.drawable.ic_mic);
        }
    });
}

So if I click a button, and scroll to the bottom of the list, the sounds get interrupted. I think it is interrupted because this List Item is out of screen and is garbage collected.

How I can make this sound play till the end, even if I scroll ListView to bottom, or switch views?

You want to create a separate thread which holds your MediaPlayer object. When you click on the button, send a message to that thread telling it what audio resource you want to play.

The easiest way to do this is probably using an Handler object, which will manage your thread and create a message queue for communicating with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM