我已经在脚本中添加了.release()方法并运行了android仿真器,在运行时,我查看了android监视器并开始单击textviews播放声音。

但是声音结束后没有释放记忆,我做错了什么?

package com.example.android.miwok;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

public class NumbersActivity extends AppCompatActivity {

private MediaPlayer mMediaPlayer;

private MediaPlayer.OnCompletionListener mCompletionListerner = new MediaPlayer.OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        releaseMediaPlayer();
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.word_list);

    final ArrayList<Word> words = new ArrayList<>();    // <-- Creates list

    words.add(new Word("one", "lutti", R.raw.number_one, R.drawable.number_one));
    words.add(new Word("two", "otiiko", R.raw.number_two, R.drawable.number_two));
    words.add(new Word("three", "tolookosu", R.raw.number_three, R.drawable.number_three));
    words.add(new Word("four", "oyyisa", R.raw.number_four, R.drawable.number_four));
    words.add(new Word("five", "massokka", R.raw.number_five, R.drawable.number_five));
    words.add(new Word("six", "temmokka", R.raw.number_six, R.drawable.number_six));
    words.add(new Word("seven", "kenekaku", R.raw.number_seven, R.drawable.number_seven));
    words.add(new Word("eight", "kawinta", R.raw.number_eight, R.drawable.number_eight));
    words.add(new Word("nine", "wo'e", R.raw.number_nine, R.drawable.number_nine));
    words.add(new Word("ten", "na'aacha", R.raw.number_ten, R.drawable.number_ten));

    WordAdapter adapter = new WordAdapter(this, words, R.color.category_numbers);


    ListView listView = (ListView) findViewById(R.id.list);     // <-- id the Listview
    listView.setAdapter(adapter);

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            releaseMediaPlayer();
            Word word = words.get(position);
            mMediaPlayer = MediaPlayer.create(NumbersActivity.this, word.getAudioResourceId());
            mMediaPlayer.start();
            mMediaPlayer.setOnCompletionListener(mCompletionListerner);
        }
    });
}

private void releaseMediaPlayer() {
    if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
}
}

最佳答案

Android(更常见的Java)使用Garbage Collector系统。

该收集器不会立即“收集”可用内存,您无法精确确定何时将通过!因此,当您.release()一个对象或其他任何对象时,您将不得不等待,直到GC决定是时候该解决了。

释放引用的唯一作用是告诉GC该对象可以被垃圾回收...就这样;)

因此,回答您的问题:您没有做错任何事情,您只需要等待并希望获得GC。

关于java - 查看安卓监视器图时,.release()不会减少我的内存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38984220/

10-16 18:41