I am trying to use the WeakReference
class to prevent from having memory leaks in Android.
I have designed a Bluetooth API that allows two Android devices to communicate (a client and a server) using the Android Bluetooth SDK.
This API is available whithin a shared library (so both apps have access to the same code).
The problem here is that the reference inside my weakreferences gets destroyed in matters of seconds. I tried to use a custom ReferenceQueue
but none of its methods are called!
Looking at the RAM usage of both Android devices I don't see anything scary : very low, very stable, because I have a single Activity with a few views.
I thought the WeakReference
is supposed to keep a reference of my Activities as long as they don't get garbage collected (meaning, there is no strong reference anymore). Am I wrong ?
[EDIT 1]
To provide more clarifications, I will post some theoretical code that should represent what I am attempting to do.
Class BluetoothAPI
private WeakReference<BluetoothStateListener> stateListener;
public final void setProgressListener(@Nullable BluetoothProgressListener progressListener) {
this.progressListener = new WeakReference<>(progressListener, new Ref<>(context));
}
private synchronized void notifyProgress(final float percent) {
if (this.progressListener != null) {
final BluetoothProgressListener listener = this.progressListener.get();
if (listener != null) {
UIAccess.runOnUiThread(new Runnable() {
public final void run() {
listener.onProgress(percent);
}
});
} else {
Log.d(TAG, "Progress Listener is null!");
}
}
}
Class Activity A, inside onCreate()
this.btAPI.setProgressListener(new BluetoothProgressListener() {
@UiThread
public final void onProgress(final float percent) {
final int progress = Math.round(percent * 10);
progressBar.setProgress(progress);
progressLabel.setText(getString(R.string.main_act_progress_status_tv_incoming, progress / 10));
}
});
When receiving data, my progressbar is never updated because the BluetoothProgressListener
is always null. What does justify this ?