diff options
author | jiabin <jiabin@google.com> | 2021-07-09 11:50:07 -0700 |
---|---|---|
committer | jiabin <jiabin@google.com> | 2021-07-09 14:53:26 -0700 |
commit | 0f3339cfc299fc908aad61152734ac0290b5c0e3 (patch) | |
tree | 648e727dfe244a9f8f0c137fd53b2e9ff03383fb | |
parent | f36c575bee6e45d274ebdb3cb931028695d613d9 (diff) |
Cache weak reference for static context.
Use weak reference to cache static context to avoid leak.
Test: atest RingtoneManagerTest
Test: atest RequestPinItemTest
Bug: 192995480
Change-Id: Idbfc9bd0c93ddb40693989c0d09719af24363f1d
-rw-r--r-- | media/java/android/media/AudioManager.java | 33 |
1 files changed, 19 insertions, 14 deletions
diff --git a/media/java/android/media/AudioManager.java b/media/java/android/media/AudioManager.java index 09ebb40e7ad7..bd3ca5a80f96 100644 --- a/media/java/android/media/AudioManager.java +++ b/media/java/android/media/AudioManager.java @@ -73,6 +73,7 @@ import com.android.internal.util.Preconditions; import java.io.IOException; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; @@ -103,7 +104,7 @@ public class AudioManager { private static final AudioVolumeGroupChangeHandler sAudioAudioVolumeGroupChangedHandler = new AudioVolumeGroupChangeHandler(); - private static Context sContext; + private static WeakReference<Context> sContext; /** * Broadcast intent, a hint for applications that audio is about to become @@ -800,7 +801,7 @@ public class AudioManager { } else { mOriginalContext = context; } - sContext = context; + sContext = new WeakReference<>(context); } @UnsupportedAppUsage @@ -7256,23 +7257,27 @@ public class AudioManager { */ public static boolean hasHapticChannels(@Nullable Context context, @NonNull Uri uri) { Objects.requireNonNull(uri); + if (context != null) { return hasHapticChannelsImpl(context, uri); - } else if (sContext != null) { + } + + Context cachedContext = sContext.get(); + if (cachedContext != null) { if (DEBUG) { Log.d(TAG, "Try to use static context to query if having haptic channels"); } - return hasHapticChannelsImpl(sContext, uri); - } else { - // Try with audio service context, this may fail to get correct result. - if (DEBUG) { - Log.d(TAG, "Try to use audio service context to query if having haptic channels"); - } - try { - return getService().hasHapticChannels(uri); - } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); - } + return hasHapticChannelsImpl(cachedContext, uri); + } + + // Try with audio service context, this may fail to get correct result. + if (DEBUG) { + Log.d(TAG, "Try to use audio service context to query if having haptic channels"); + } + try { + return getService().hasHapticChannels(uri); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); } } |