hyu*_*cho 3 java android weak-references arraylist
我的应用程序相机预览记录应用程序。我ArrayList在录制相机预览期间使用 , 。
ArrayList在全局变量上声明
private ArrayList<OutputInputPair> pairs = new ArrayList<OutputInput>();
当我记录停止按钮单击时,执行stop()方法
@Override
public void stop() {
pairs.clear();
pairs = null;
stopped = true;
}
Run Code Online (Sandbox Code Playgroud)
所以,如果我继续录制而不单击录制停止按钮。发生大量内存泄漏。
所以,我想用WeakReference
我试试这个
//private ArrayList<OutputInputPair> pairs = new ArrayList<OutputInputPair();
private ArrayList<WeakReference<OutputInputPair>> pairs = new ArrayList<WeakReference<OutputInputPair>>(); //global variable
@Override
public void add(OutputInputPair pair) {
//pairs.add(pair);
pairs.add(new WeakReference<OutputInputPair>(pair));
}
@Override
public void stop() {
pairs.clear();
pairs = null;
stopped = true;
}
@Override
public void process() { //record method
//for (OutputInputPair pair : pairs) {
for (WeakReference<OutputInputPair> pair = pairs) {
pair.output.fillCommandQueues(); //output is cannot resolve symbol message
pair.input.fillCommandQueues(); //input is cannot resolve symbol message
}
while (!stopped) { //when user click stop button, stopped = true.
//for (OutputInputPair pair : pairs) {
for (WeakReference<OutputInputPair> pair : pairs) {
recording(pair); //start recording
}
}
}
public interface IOutputRaw { //IInputRaw class same code.
void fillCommandQueues();
}
Run Code Online (Sandbox Code Playgroud)
我想如何避免内存不足,使用WeakReference是否正确?
如何修复无法解析符号消息使用弱引用?
谢谢。
public class OutputInputPair {
public IOutputRaw output;
public IInputRaw input;
public OutputInputPair(IOutputRaw output, IInputRaw input) {
this.output = output;
this.input = input;
}
}
Run Code Online (Sandbox Code Playgroud)
我了解的不多WeakReference。但您应该使用该get()方法来获取实际参考。
使用:
if(pair == null) continue;
OutputInputPair actualPair = pair.get();
if(actualPair == null) continue;
actualPair.output.fillCommandQueues();
actualPair.input.fillCommandQueues();
Run Code Online (Sandbox Code Playgroud)
代替:
pair.output.fillCommandQueues();
pair.input.fillCommandQueues();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
636 次 |
| 最近记录: |