Android 泄漏:计时器和文本监视程序
我正在做一个editText和一个recyclerView。 当我在编辑文本中写信时,我的recyclerView会更新 我在textWatcher中设置了一个计时器,以避免每次用户写信时都发送请求Android 泄漏:计时器和文本监视程序,android,memory-leaks,timer,textwatcher,Android,Memory Leaks,Timer,Textwatcher,我正在做一个editText和一个recyclerView。 当我在编辑文本中写信时,我的recyclerView会更新 我在textWatcher中设置了一个计时器,以避免每次用户写信时都发送请求 searchDestinationEt.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(final CharSequence s, final int
searchDestinationEt.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) {
//There is nothing to do here
}
@Override
public void onTextChanged(final CharSequence s, final int start, final int before, final int count) {
if (timer != null) {
timer.cancel();
}
}
@Override
public void afterTextChanged(final Editable s) {
timer = new Timer();
//we schedule this in order to avoid sending useless request.
//We wait the user is finishing writing before sending requests
timer.schedule(new TimerTask() {
@Override
public void run() {
((Activity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
actionsListener.onDestinationSearch(s.toString());
}
});
}
}, DELAY_SEND_REQUEST);
}
});
它工作得很好,但是leakcanary说我在这部分代码中有漏洞。
有什么想法吗?很抱歉回复晚了,但您是否尝试过这样分离textwatcher
Timer
和TimerTask
进行延迟而非重复的操作?最简单也是最常见的方法是只使用常规的处理程序和postDelayed()
:
AsyncTask
可能更合适private static class SomeWorkTask extends AsyncTask<Void,Void,Void>{
private WeakReference<ActionsListenerWithContext> weakListener;
public SomeWorkTask(ActionsListenerWithContext listener){
this.weakListener = new WeakReference<>(listener);
}
@Override
protected Void doInBackground(Void... voids) {
//do some work here
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if(weakListener.get() != null){
weakListener.get().callYourCallbacks();
}
}
}
使用
WeakReference
包装器是一种常见的推荐做法 @oiZo Thx,我会试试的。但这并不能解释为什么会有泄漏:/。
private static class SomeWorkTask extends AsyncTask<Void,Void,Void>{
private WeakReference<ActionsListenerWithContext> weakListener;
public SomeWorkTask(ActionsListenerWithContext listener){
this.weakListener = new WeakReference<>(listener);
}
@Override
protected Void doInBackground(Void... voids) {
//do some work here
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
if(weakListener.get() != null){
weakListener.get().callYourCallbacks();
}
}
}
new SomeWorkTask(listener).execute();