Donate to e Foundation | Murena handsets with /e/OS | Own a part of Murena! Learn more

Commit a6e3edc5 authored by Bishoy Gendy's avatar Bishoy Gendy
Browse files

Implement equals and hashcode for MediaSessionRecord(s)

- This involves changing MediaSessionRecordImpl into an abstract class.

Bug: 295518668
Bug: 297052684
Test: atest CtsMediaBetterTogetherTestCases MediaRouter2HostSideTest
Change-Id: I1f7f9da7c689093ab5df6ef26d255e56c36486f7
parent babbcd96
Loading
Loading
Loading
Loading
+5 −14
Original line number Diff line number Diff line
@@ -35,12 +35,11 @@ import java.io.PrintWriter;
 * Keeps the record of {@link Session2Token} to help send command to the corresponding session.
 */
// TODO(jaewan): Do not call service method directly -- introduce listener instead.
public class MediaSession2Record implements MediaSessionRecordImpl {
public class MediaSession2Record extends MediaSessionRecordImpl {
    private static final String TAG = "MediaSession2Record";
    private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
    private final Object mLock = new Object();

    private final int mUniqueId;
    @GuardedBy("mLock")
    private final Session2Token mSessionToken;
    @GuardedBy("mLock")
@@ -64,13 +63,12 @@ public class MediaSession2Record implements MediaSessionRecordImpl {
            MediaSessionService service,
            Looper handlerLooper,
            int pid,
            int policies,
            int uniqueId) {
            int policies) {
        // The lock is required to prevent `Controller2Callback` from using partially initialized
        // `MediaSession2Record.this`.
        synchronized (mLock) {
            mUniqueId = sNextMediaSessionRecordId.getAndIncrement();
            mSessionToken = sessionToken;
            mUniqueId = uniqueId;
            mService = service;
            mHandlerExecutor = new HandlerExecutor(new Handler(handlerLooper));
            mController = new MediaController2.Builder(service.getContext(), sessionToken)
@@ -100,13 +98,6 @@ public class MediaSession2Record implements MediaSessionRecordImpl {
        }
    }

    @Override
    public int getUniqueId() {
        synchronized (mLock) {
            return mUniqueId;
        }
    }

    @Override
    public String getPackageName() {
        return mSessionToken.getPackageName();
@@ -210,7 +201,7 @@ public class MediaSession2Record implements MediaSessionRecordImpl {

    @Override
    public void dump(PrintWriter pw, String prefix) {
        pw.println(prefix + "uniqueId=" + mUniqueId);
        pw.println(prefix + "uniqueId=" + getUniqueId());
        pw.println(prefix + "token=" + mSessionToken);
        pw.println(prefix + "controller=" + mController);

@@ -220,7 +211,7 @@ public class MediaSession2Record implements MediaSessionRecordImpl {

    @Override
    public String toString() {
        return getPackageName() + "/" + mUniqueId + " (userId=" + getUserId() + ")";
        return getPackageName() + "/" + getUniqueId() + " (userId=" + getUserId() + ")";
    }

    private class Controller2Callback extends MediaController2.ControllerCallback {
+3 −15
Original line number Diff line number Diff line
@@ -96,7 +96,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
 * MediaSession wrapper class instead.
 */
// TODO(jaewan): Do not call service method directly -- introduce listener instead.
public class MediaSessionRecord implements IBinder.DeathRecipient, MediaSessionRecordImpl {
public class MediaSessionRecord extends MediaSessionRecordImpl implements IBinder.DeathRecipient {

    /**
     * {@link android.media.session.MediaSession#setMediaButtonBroadcastReceiver(
@@ -173,7 +173,6 @@ public class MediaSessionRecord implements IBinder.DeathRecipient, MediaSessionR
    private final int mUserId;
    private final String mPackageName;
    private final String mTag;
    private final int mUniqueId;
    private final Bundle mSessionInfo;
    private final ControllerStub mController;
    private final MediaSession.Token mSessionToken;
@@ -231,18 +230,17 @@ public class MediaSessionRecord implements IBinder.DeathRecipient, MediaSessionR
            String ownerPackageName,
            ISessionCallback cb,
            String tag,
            int uniqueId,
            Bundle sessionInfo,
            MediaSessionService service,
            Looper handlerLooper,
            int policies)
            throws RemoteException {
        mUniqueId = sNextMediaSessionRecordId.getAndIncrement();
        mOwnerPid = ownerPid;
        mOwnerUid = ownerUid;
        mUserId = userId;
        mPackageName = ownerPackageName;
        mTag = tag;
        mUniqueId = uniqueId;
        mSessionInfo = sessionInfo;
        mController = new ControllerStub();
        mSessionToken = new MediaSession.Token(ownerUid, mController);
@@ -302,16 +300,6 @@ public class MediaSessionRecord implements IBinder.DeathRecipient, MediaSessionR
        return mSessionToken;
    }

    /**
     * Get the unique id of this session record.
     *
     * @return a unique id of this session record.
     */
    @Override
    public int getUniqueId() {
        return mUniqueId;
    }

    /**
     * Get the info for this session.
     *
@@ -724,7 +712,7 @@ public class MediaSessionRecord implements IBinder.DeathRecipient, MediaSessionR

    @Override
    public String toString() {
        return mPackageName + "/" + mTag + "/" + mUniqueId + " (userId=" + mUserId + ")";
        return mPackageName + "/" + mTag + "/" + getUniqueId() + " (userId=" + mUserId + ")";
    }

    @Override
+45 −26
Original line number Diff line number Diff line
@@ -25,39 +25,37 @@ import android.view.KeyEvent;
import com.android.server.media.MediaSessionPolicyProvider.SessionPolicy;

import java.io.PrintWriter;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Common interfaces between {@link MediaSessionRecord} and {@link MediaSession2Record}.
 */
public interface MediaSessionRecordImpl extends AutoCloseable {
public abstract class MediaSessionRecordImpl {

    /**
     * Get the unique id of this session record.
     *
     * @return a unique id of this session record.
     */
    int getUniqueId();
    static final AtomicInteger sNextMediaSessionRecordId = new AtomicInteger(1);
    int mUniqueId;

    /**
     * Get the info for this session.
     *
     * @return Info that identifies this session.
     */
    String getPackageName();
    public abstract String getPackageName();

    /**
     * Get the UID this session was created for.
     *
     * @return The UID for this session.
     */
    int getUid();
    public abstract int getUid();

    /**
     * Get the user id this session was created for.
     *
     * @return The user id for this session.
     */
    int getUserId();
    public abstract int getUserId();

    /**
     * Get the {@link ForegroundServiceDelegationOptions} needed for notifying activity manager
@@ -66,7 +64,7 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     * @return the {@link ForegroundServiceDelegationOptions} needed for notifying the activity
     *     manager service with changes in the {@link PlaybackState} for this session.
     */
    ForegroundServiceDelegationOptions getForegroundServiceDelegationOptions();
    public abstract ForegroundServiceDelegationOptions getForegroundServiceDelegationOptions();

    /**
     * Check if this session has system priority and should receive media buttons before any other
@@ -74,7 +72,7 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     *
     * @return True if this is a system priority session, false otherwise
     */
    boolean isSystemPriority();
    public abstract boolean isSystemPriority();

    /**
     * Send a volume adjustment to the session owner. Direction must be one of
@@ -95,7 +93,7 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     * @param useSuggested True to use adjustSuggestedStreamVolumeForUid instead of
     *          adjustStreamVolumeForUid
     */
    void adjustVolume(String packageName, String opPackageName, int pid, int uid,
    public abstract void adjustVolume(String packageName, String opPackageName, int pid, int uid,
            boolean asSystemService, int direction, int flags, boolean useSuggested);

    /**
@@ -105,7 +103,7 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     * @return True if the session is active, false otherwise.
     */
    // TODO(jaewan): Find better naming, or remove this from the MediaSessionRecordImpl.
    boolean isActive();
    public abstract boolean isActive();

    /**
     * Check if the session's playback active state matches with the expectation. This always
@@ -115,7 +113,7 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     * @param expected True if playback is expected to be active. False otherwise.
     * @return True if the session's playback matches with the expectation. False otherwise.
     */
    boolean checkPlaybackActiveState(boolean expected);
    public abstract boolean checkPlaybackActiveState(boolean expected);

    /**
     * Check whether the playback type is local or remote.
@@ -128,7 +126,7 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     *
     * @return {@code true} if the playback is local. {@code false} if the playback is remote.
     */
    boolean isPlaybackTypeLocal();
    public abstract boolean isPlaybackTypeLocal();

    /**
     * Sends media button.
@@ -145,27 +143,27 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     * @return {@code true} if the attempt to send media button was successfully.
     *         {@code false} otherwise.
     */
    boolean sendMediaButton(String packageName, int pid, int uid, boolean asSystemService,
            KeyEvent ke, int sequenceId, ResultReceiver cb);
    public abstract boolean sendMediaButton(String packageName, int pid, int uid,
            boolean asSystemService, KeyEvent ke, int sequenceId, ResultReceiver cb);

    /**
     * Returns whether the media session can handle volume key events.
     *
     * @return True if this media session can handle volume key events, false otherwise.
     */
    boolean canHandleVolumeKey();
    public abstract boolean canHandleVolumeKey();

    /**
     * Get session policies from custom policy provider set when MediaSessionRecord is instantiated.
     * If custom policy does not exist, will return null.
     */
    @SessionPolicy
    int getSessionPolicies();
    public abstract int getSessionPolicies();

    /**
     * Overwrite session policies that have been set when MediaSessionRecord is instantiated.
     */
    void setSessionPolicies(@SessionPolicy int policies);
    public abstract void setSessionPolicies(@SessionPolicy int policies);

    /**
     * Dumps internal state
@@ -173,16 +171,37 @@ public interface MediaSessionRecordImpl extends AutoCloseable {
     * @param pw print writer
     * @param prefix prefix
     */
    void dump(PrintWriter pw, String prefix);
    public abstract void dump(PrintWriter pw, String prefix);

    /**
     * Override {@link AutoCloseable#close} to tell it not to throw exception.
     * Similar to {@link AutoCloseable#close} without throwing an exception.
     */
    @Override
    void close();
    public abstract void close();

    /**
     * Get the unique id of this session record.
     *
     * @return a unique id of this session record.
     */
    public int getUniqueId() {
        return mUniqueId;
    }

    /**
     * Returns whether {@link #close()} is called before.
     */
    boolean isClosed();
    public abstract boolean isClosed();

    @Override
    public final boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || !(o instanceof MediaSessionRecordImpl)) return false;
        MediaSessionRecordImpl that = (MediaSessionRecordImpl) o;
        return mUniqueId == that.mUniqueId;
    }

    @Override
    public final int hashCode() {
        return Objects.hash(mUniqueId);
    }
}
+1 −6
Original line number Diff line number Diff line
@@ -106,7 +106,6 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * System implementation of MediaSessionManager
@@ -156,8 +155,6 @@ public class MediaSessionService extends SystemService implements Monitor {
    /* Maps uid with all user engaging session tokens associated to it */
    private final SparseArray<Set<MediaSession.Token>> mUserEngagingSessions = new SparseArray<>();

    private final AtomicInteger mNextMediaSessionRecordId = new AtomicInteger(1);

    // The FullUserRecord of the current users. (i.e. The foreground user that isn't a profile)
    // It's always not null after the MediaSessionService is started.
    private FullUserRecord mCurrentFullUserRecord;
@@ -196,8 +193,7 @@ public class MediaSessionService extends SystemService implements Monitor {
                                    MediaSessionService.this,
                                    mRecordThread.getLooper(),
                                    pid,
                                    /* policies= */ 0,
                                    /* uniqueId= */ mNextMediaSessionRecordId.getAndIncrement());
                                    /* policies= */ 0);
                    synchronized (mLock) {
                        FullUserRecord user = getFullUserRecordLocked(record.getUserId());
                        if (user != null) {
@@ -806,7 +802,6 @@ public class MediaSessionService extends SystemService implements Monitor {
                                callerPackageName,
                                cb,
                                tag,
                                /* uniqueId= */ mNextMediaSessionRecordId.getAndIncrement(),
                                sessionInfo,
                                this,
                                mRecordThread.getLooper(),