blob: a3c6c80c75aa2c204391a3c6690af6a15476bb7c [file] [log] [blame]
RoboErik01fe6612014-02-13 14:19:04 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.media;
18
Jaewan Kimf7a77062018-01-27 01:34:24 +090019import static android.media.SessionToken2.TYPE_SESSION;
20
RoboErike7880d82014-04-30 12:48:25 -070021import android.app.ActivityManager;
Jaewan Kimfed49502018-03-05 17:51:12 +090022import android.app.AppGlobals;
Julia Reynoldsb852e562017-06-06 16:14:18 -040023import android.app.INotificationManager;
RoboErik9a9d0b52014-05-20 14:53:39 -070024import android.app.KeyguardManager;
RoboErikb214efb2014-07-24 13:20:30 -070025import android.app.PendingIntent;
26import android.app.PendingIntent.CanceledException;
RoboErik9a9d0b52014-05-20 14:53:39 -070027import android.content.ActivityNotFoundException;
RoboErik8a2cfc32014-05-16 11:19:38 -070028import android.content.BroadcastReceiver;
RoboErike7880d82014-04-30 12:48:25 -070029import android.content.ComponentName;
RoboErik6f0e4dd2014-06-17 16:56:27 -070030import android.content.ContentResolver;
RoboErik01fe6612014-02-13 14:19:04 -080031import android.content.Context;
RoboErik8a2cfc32014-05-16 11:19:38 -070032import android.content.Intent;
Jaewan Kim66d451b2018-02-12 21:23:06 +090033import android.content.IntentFilter;
Jaewan Kimfed49502018-03-05 17:51:12 +090034import android.content.pm.IPackageManager;
RoboErika278ea72014-04-24 14:49:01 -070035import android.content.pm.PackageManager;
Jaewan Kimf7a77062018-01-27 01:34:24 +090036import android.content.pm.PackageManager.NameNotFoundException;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +090037import android.content.pm.ResolveInfo;
38import android.content.pm.ServiceInfo;
Jaewan Kima7dce192017-02-16 17:10:54 +090039import android.content.pm.UserInfo;
RoboErik7aef77b2014-08-08 15:56:54 -070040import android.database.ContentObserver;
RoboErik3c45c292014-07-08 16:47:31 -070041import android.media.AudioManager;
Sungsoo Lim875e6972017-11-03 02:22:35 +000042import android.media.AudioPlaybackConfiguration;
RoboErik94c716e2014-09-14 13:54:31 -070043import android.media.AudioSystem;
RoboErikb69ffd42014-05-30 14:57:59 -070044import android.media.IAudioService;
RoboErik19c95182014-06-23 15:38:48 -070045import android.media.IRemoteVolumeController;
Jaewan Kim379e30d2018-01-29 11:57:04 +090046import android.media.ISessionTokensListener;
Sungsoo Lim117c7f72018-02-13 16:02:24 +090047import android.media.MediaController2;
Jaewan Kimbcecf312018-01-23 19:30:42 +090048import android.media.MediaLibraryService2;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +090049import android.media.MediaSessionService2;
Jaewan Kim04de5de2018-01-25 02:24:03 +090050import android.media.SessionToken2;
RoboErik2e7a9162014-06-04 16:53:45 -070051import android.media.session.IActiveSessionsListener;
Jaewan Kimbd16f452017-02-03 16:21:38 +090052import android.media.session.ICallback;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080053import android.media.session.IOnMediaKeyListener;
Jaewan Kim50269362016-12-23 11:22:02 +090054import android.media.session.IOnVolumeKeyLongPressListener;
RoboErik07c70772014-03-20 13:33:52 -070055import android.media.session.ISession;
56import android.media.session.ISessionCallback;
57import android.media.session.ISessionManager;
Jeff Browndba34ba2014-06-24 20:46:03 -070058import android.media.session.MediaSession;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080059import android.media.session.MediaSessionManager;
RoboErik7aef77b2014-08-08 15:56:54 -070060import android.net.Uri;
RoboErik01fe6612014-02-13 14:19:04 -080061import android.os.Binder;
RoboErik8a2cfc32014-05-16 11:19:38 -070062import android.os.Bundle;
RoboErik8ae0f342014-02-24 18:02:08 -080063import android.os.Handler;
RoboErike7880d82014-04-30 12:48:25 -070064import android.os.IBinder;
RoboErik2e7a9162014-06-04 16:53:45 -070065import android.os.Message;
RoboErik8a2cfc32014-05-16 11:19:38 -070066import android.os.PowerManager;
Jaewan Kim8f729082016-06-21 12:36:26 +090067import android.os.Process;
RoboErik01fe6612014-02-13 14:19:04 -080068import android.os.RemoteException;
RoboErik8a2cfc32014-05-16 11:19:38 -070069import android.os.ResultReceiver;
RoboErikb69ffd42014-05-30 14:57:59 -070070import android.os.ServiceManager;
RoboErike7880d82014-04-30 12:48:25 -070071import android.os.UserHandle;
Jaewan Kim8f729082016-06-21 12:36:26 +090072import android.os.UserManager;
RoboErike7880d82014-04-30 12:48:25 -070073import android.provider.Settings;
RoboErik9a9d0b52014-05-20 14:53:39 -070074import android.speech.RecognizerIntent;
RoboErik01fe6612014-02-13 14:19:04 -080075import android.text.TextUtils;
Sungsoo Lim117c7f72018-02-13 16:02:24 +090076import android.util.ArrayMap;
RoboErik01fe6612014-02-13 14:19:04 -080077import android.util.Log;
Jeff Brown38d3feb2015-03-19 18:26:30 -070078import android.util.Slog;
RoboErik4646d282014-05-13 10:13:04 -070079import android.util.SparseArray;
Jaewan Kima7dce192017-02-16 17:10:54 +090080import android.util.SparseIntArray;
RoboErik8a2cfc32014-05-16 11:19:38 -070081import android.view.KeyEvent;
Jaewan Kimd61a87b2017-02-17 23:14:10 +090082import android.view.ViewConfiguration;
RoboErik01fe6612014-02-13 14:19:04 -080083
Jaewan Kim66d451b2018-02-12 21:23:06 +090084import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060085import com.android.internal.util.DumpUtils;
RoboErik01fe6612014-02-13 14:19:04 -080086import com.android.server.SystemService;
RoboErika278ea72014-04-24 14:49:01 -070087import com.android.server.Watchdog;
88import com.android.server.Watchdog.Monitor;
RoboErik01fe6612014-02-13 14:19:04 -080089
RoboErika278ea72014-04-24 14:49:01 -070090import java.io.FileDescriptor;
91import java.io.PrintWriter;
RoboErik01fe6612014-02-13 14:19:04 -080092import java.util.ArrayList;
Sungsoo Lim117c7f72018-02-13 16:02:24 +090093import java.util.HashSet;
RoboErike7880d82014-04-30 12:48:25 -070094import java.util.List;
Sungsoo Lim117c7f72018-02-13 16:02:24 +090095import java.util.Map;
96import java.util.Set;
Sungsoo Lim375efa12018-03-02 10:17:08 +090097import java.util.NoSuchElementException;
RoboErik01fe6612014-02-13 14:19:04 -080098
99/**
100 * System implementation of MediaSessionManager
101 */
RoboErika278ea72014-04-24 14:49:01 -0700102public class MediaSessionService extends SystemService implements Monitor {
RoboErik01fe6612014-02-13 14:19:04 -0800103 private static final String TAG = "MediaSessionService";
Jaewan Kim129a5622018-03-28 12:19:04 +0900104 static final boolean USE_MEDIA2_APIS = false; // TODO: Change this to true when we're ready.
Jaewan Kim92dea332017-02-02 11:52:08 +0900105 static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jaewan Kim50269362016-12-23 11:22:02 +0900106 // Leave log for key event always.
107 private static final boolean DEBUG_KEY_EVENT = true;
RoboErik01fe6612014-02-13 14:19:04 -0800108
RoboErik418c10c2014-05-19 09:25:25 -0700109 private static final int WAKELOCK_TIMEOUT = 5000;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800110 private static final int MEDIA_KEY_LISTENER_TIMEOUT = 1000;
RoboErik418c10c2014-05-19 09:25:25 -0700111
RoboErik01fe6612014-02-13 14:19:04 -0800112 private final SessionManagerImpl mSessionManagerImpl;
113
Jaewan Kima7dce192017-02-16 17:10:54 +0900114 // Keeps the full user id for each user.
115 private final SparseIntArray mFullUserIds = new SparseIntArray();
116 private final SparseArray<FullUserRecord> mUserRecords = new SparseArray<FullUserRecord>();
RoboErik2e7a9162014-06-04 16:53:45 -0700117 private final ArrayList<SessionsListenerRecord> mSessionsListeners
118 = new ArrayList<SessionsListenerRecord>();
RoboErik01fe6612014-02-13 14:19:04 -0800119 private final Object mLock = new Object();
RoboErik2e7a9162014-06-04 16:53:45 -0700120 private final MessageHandler mHandler = new MessageHandler();
RoboErik8a2cfc32014-05-16 11:19:38 -0700121 private final PowerManager.WakeLock mMediaEventWakeLock;
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900122 private final int mLongPressTimeout;
Jaewan Kimfed49502018-03-05 17:51:12 +0900123 private final INotificationManager mNotificationManager;
124 private final IPackageManager mPackageManager;
RoboErik01fe6612014-02-13 14:19:04 -0800125
RoboErik9a9d0b52014-05-20 14:53:39 -0700126 private KeyguardManager mKeyguardManager;
RoboErikb69ffd42014-05-30 14:57:59 -0700127 private IAudioService mAudioService;
RoboErik6f0e4dd2014-06-17 16:56:27 -0700128 private ContentResolver mContentResolver;
RoboErik7aef77b2014-08-08 15:56:54 -0700129 private SettingsObserver mSettingsObserver;
Jaewan Kimfdb612e2017-07-01 09:23:41 +0900130 private boolean mHasFeatureLeanback;
RoboErik9a9d0b52014-05-20 14:53:39 -0700131
Jaewan Kima7dce192017-02-16 17:10:54 +0900132 // The FullUserRecord of the current users. (i.e. The foreground user that isn't a profile)
133 // It's always not null after the MediaSessionService is started.
134 private FullUserRecord mCurrentFullUserRecord;
135 private MediaSessionRecord mGlobalPrioritySession;
Sungsoo Lim875e6972017-11-03 02:22:35 +0000136 private AudioPlayerStateMonitor mAudioPlayerStateMonitor;
RoboErike7880d82014-04-30 12:48:25 -0700137
RoboErik19c95182014-06-23 15:38:48 -0700138 // Used to notify system UI when remote volume was changed. TODO find a
139 // better way to handle this.
140 private IRemoteVolumeController mRvc;
141
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900142 // MediaSession2 support
Jaewan Kim005e2bb2018-03-02 15:55:12 +0900143 // TODO(jaewan): Support multi-user and managed profile. (b/73597722)
144 // TODO(jaewan): Make it priority list for handling volume/media key. (b/73760382)
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900145 private final Map<SessionToken2, MediaController2> mSessionRecords = new ArrayMap<>();
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900146
Sungsoo Lim375efa12018-03-02 10:17:08 +0900147 private final List<SessionTokensListenerRecord> mSessionTokensListeners = new ArrayList<>();
148
RoboErik01fe6612014-02-13 14:19:04 -0800149 public MediaSessionService(Context context) {
150 super(context);
151 mSessionManagerImpl = new SessionManagerImpl();
RoboErik8a2cfc32014-05-16 11:19:38 -0700152 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
153 mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900154 mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
Julia Reynoldsb852e562017-06-06 16:14:18 -0400155 mNotificationManager = INotificationManager.Stub.asInterface(
156 ServiceManager.getService(Context.NOTIFICATION_SERVICE));
Jaewan Kimfed49502018-03-05 17:51:12 +0900157 mPackageManager = AppGlobals.getPackageManager();
RoboErik01fe6612014-02-13 14:19:04 -0800158 }
159
160 @Override
161 public void onStart() {
162 publishBinderService(Context.MEDIA_SESSION_SERVICE, mSessionManagerImpl);
RoboErika278ea72014-04-24 14:49:01 -0700163 Watchdog.getInstance().addMonitor(this);
RoboErik9a9d0b52014-05-20 14:53:39 -0700164 mKeyguardManager =
165 (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
RoboErikb69ffd42014-05-30 14:57:59 -0700166 mAudioService = getAudioService();
Sungsoo Lim875e6972017-11-03 02:22:35 +0000167 mAudioPlayerStateMonitor = AudioPlayerStateMonitor.getInstance();
168 mAudioPlayerStateMonitor.registerListener(
Sungsoo Lim2afdbc42017-11-01 13:45:59 +0900169 (config, isRemoved) -> {
170 if (isRemoved || !config.isActive() || config.getPlayerType()
171 == AudioPlaybackConfiguration.PLAYER_TYPE_JAM_SOUNDPOOL) {
172 return;
Jaewan Kim92dea332017-02-02 11:52:08 +0900173 }
Sungsoo Lim2afdbc42017-11-01 13:45:59 +0900174 synchronized (mLock) {
175 FullUserRecord user = getFullUserRecordLocked(
176 UserHandle.getUserId(config.getClientUid()));
177 if (user != null) {
178 user.mPriorityStack.updateMediaButtonSessionIfNeeded();
179 }
180 }
181 }, null /* handler */);
Sungsoo Lim875e6972017-11-03 02:22:35 +0000182 mAudioPlayerStateMonitor.registerSelfIntoAudioServiceIfNeeded(mAudioService);
RoboErik6f0e4dd2014-06-17 16:56:27 -0700183 mContentResolver = getContext().getContentResolver();
RoboErik7aef77b2014-08-08 15:56:54 -0700184 mSettingsObserver = new SettingsObserver();
185 mSettingsObserver.observe();
Jaewan Kimfdb612e2017-07-01 09:23:41 +0900186 mHasFeatureLeanback = getContext().getPackageManager().hasSystemFeature(
187 PackageManager.FEATURE_LEANBACK);
RoboErikc8f92d12015-01-05 16:48:07 -0800188
189 updateUser();
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900190
Jaewan Kim66d451b2018-02-12 21:23:06 +0900191 registerPackageBroadcastReceivers();
Jaewan Kim005e2bb2018-03-02 15:55:12 +0900192 // TODO(jaewan): Query per users (b/73597722)
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900193 buildMediaSessionService2List();
RoboErikb69ffd42014-05-30 14:57:59 -0700194 }
195
196 private IAudioService getAudioService() {
197 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
198 return IAudioService.Stub.asInterface(b);
RoboErik07c70772014-03-20 13:33:52 -0700199 }
200
Jaewan Kima7dce192017-02-16 17:10:54 +0900201 private boolean isGlobalPriorityActiveLocked() {
202 return mGlobalPrioritySession != null && mGlobalPrioritySession.isActive();
203 }
204
RoboErika8f95142014-05-05 14:23:49 -0700205 public void updateSession(MediaSessionRecord record) {
RoboErike7880d82014-04-30 12:48:25 -0700206 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900207 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
Jaewan Kim101b4d52017-05-18 13:23:11 +0900208 if (user == null) {
209 Log.w(TAG, "Unknown session updated. Ignoring.");
RoboErik4646d282014-05-13 10:13:04 -0700210 return;
211 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900212 if ((record.getFlags() & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
Jaewan Kim101b4d52017-05-18 13:23:11 +0900213 if (DEBUG_KEY_EVENT) {
214 Log.d(TAG, "Global priority session is updated, active=" + record.isActive());
215 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900216 user.pushAddressedPlayerChangedLocked();
Jaewan Kim101b4d52017-05-18 13:23:11 +0900217 } else {
218 if (!user.mPriorityStack.contains(record)) {
219 Log.w(TAG, "Unknown session updated. Ignoring.");
220 return;
221 }
222 user.mPriorityStack.onSessionStateChange(record);
Jaewan Kima7dce192017-02-16 17:10:54 +0900223 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900224 mHandler.postSessionsChanged(record.getUserId());
RoboErike7880d82014-04-30 12:48:25 -0700225 }
226 }
227
Jaewan Kimfa85b602017-10-10 16:49:58 +0900228 public void setGlobalPrioritySession(MediaSessionRecord record) {
229 synchronized (mLock) {
230 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
231 if (mGlobalPrioritySession != record) {
232 Log.d(TAG, "Global priority session is changed from " + mGlobalPrioritySession
233 + " to " + record);
234 mGlobalPrioritySession = record;
235 if (user != null && user.mPriorityStack.contains(record)) {
236 // Handle the global priority session separately.
237 // Otherwise, it can be the media button session regardless of the active state
238 // because it or other system components might have been the lastly played media
239 // app.
240 user.mPriorityStack.removeSession(record);
241 }
242 }
243 }
244 }
245
Jaewan Kim101b4d52017-05-18 13:23:11 +0900246 private List<MediaSessionRecord> getActiveSessionsLocked(int userId) {
Jaewan Kimda74a152017-10-03 23:58:11 +0900247 List<MediaSessionRecord> records = new ArrayList<>();
Jaewan Kim101b4d52017-05-18 13:23:11 +0900248 if (userId == UserHandle.USER_ALL) {
Jaewan Kim101b4d52017-05-18 13:23:11 +0900249 int size = mUserRecords.size();
250 for (int i = 0; i < size; i++) {
251 records.addAll(mUserRecords.valueAt(i).mPriorityStack.getActiveSessions(userId));
252 }
253 } else {
254 FullUserRecord user = getFullUserRecordLocked(userId);
255 if (user == null) {
256 Log.w(TAG, "getSessions failed. Unknown user " + userId);
Jaewan Kimda74a152017-10-03 23:58:11 +0900257 return records;
Jaewan Kim101b4d52017-05-18 13:23:11 +0900258 }
Jaewan Kimda74a152017-10-03 23:58:11 +0900259 records.addAll(user.mPriorityStack.getActiveSessions(userId));
Jaewan Kim101b4d52017-05-18 13:23:11 +0900260 }
261
262 // Return global priority session at the first whenever it's asked.
263 if (isGlobalPriorityActiveLocked()
264 && (userId == UserHandle.USER_ALL
265 || userId == mGlobalPrioritySession.getUserId())) {
266 records.add(0, mGlobalPrioritySession);
267 }
268 return records;
269 }
270
RoboErik9c5b7cb2015-01-15 15:09:09 -0800271 /**
Hyundo Moona055f132017-01-13 15:31:06 +0900272 * Tells the system UI that volume has changed on an active remote session.
RoboErik9c5b7cb2015-01-15 15:09:09 -0800273 */
274 public void notifyRemoteVolumeChanged(int flags, MediaSessionRecord session) {
Hyundo Moona055f132017-01-13 15:31:06 +0900275 if (mRvc == null || !session.isActive()) {
RoboErik9c5b7cb2015-01-15 15:09:09 -0800276 return;
277 }
278 try {
279 mRvc.remoteVolumeChanged(session.getControllerBinder(), flags);
280 } catch (Exception e) {
281 Log.wtf(TAG, "Error sending volume change to system UI.", e);
282 }
283 }
284
Jaewan Kim92dea332017-02-02 11:52:08 +0900285 public void onSessionPlaystateChanged(MediaSessionRecord record, int oldState, int newState) {
RoboErika8f95142014-05-05 14:23:49 -0700286 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900287 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
288 if (user == null || !user.mPriorityStack.contains(record)) {
RoboErik4646d282014-05-13 10:13:04 -0700289 Log.d(TAG, "Unknown session changed playback state. Ignoring.");
290 return;
291 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900292 user.mPriorityStack.onPlaystateChanged(record, oldState, newState);
RoboErika8f95142014-05-05 14:23:49 -0700293 }
294 }
295
RoboErik19c95182014-06-23 15:38:48 -0700296 public void onSessionPlaybackTypeChanged(MediaSessionRecord record) {
297 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900298 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
299 if (user == null || !user.mPriorityStack.contains(record)) {
RoboErik19c95182014-06-23 15:38:48 -0700300 Log.d(TAG, "Unknown session changed playback type. Ignoring.");
301 return;
302 }
303 pushRemoteVolumeUpdateLocked(record.getUserId());
304 }
305 }
306
RoboErika278ea72014-04-24 14:49:01 -0700307 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900308 public void onStartUser(int userId) {
309 if (DEBUG) Log.d(TAG, "onStartUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700310 updateUser();
311 }
312
313 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900314 public void onSwitchUser(int userId) {
315 if (DEBUG) Log.d(TAG, "onSwitchUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700316 updateUser();
317 }
318
319 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900320 public void onStopUser(int userId) {
321 if (DEBUG) Log.d(TAG, "onStopUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700322 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900323 FullUserRecord user = getFullUserRecordLocked(userId);
RoboErik4646d282014-05-13 10:13:04 -0700324 if (user != null) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900325 if (user.mFullUserId == userId) {
326 user.destroySessionsForUserLocked(UserHandle.USER_ALL);
327 mUserRecords.remove(userId);
328 } else {
329 user.destroySessionsForUserLocked(userId);
330 }
RoboErik4646d282014-05-13 10:13:04 -0700331 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900332 updateUser();
RoboErik4646d282014-05-13 10:13:04 -0700333 }
334 }
335
336 @Override
RoboErika278ea72014-04-24 14:49:01 -0700337 public void monitor() {
338 synchronized (mLock) {
339 // Check for deadlock
340 }
341 }
342
RoboErik4646d282014-05-13 10:13:04 -0700343 protected void enforcePhoneStatePermission(int pid, int uid) {
344 if (getContext().checkPermission(android.Manifest.permission.MODIFY_PHONE_STATE, pid, uid)
345 != PackageManager.PERMISSION_GRANTED) {
346 throw new SecurityException("Must hold the MODIFY_PHONE_STATE permission.");
347 }
348 }
349
RoboErik01fe6612014-02-13 14:19:04 -0800350 void sessionDied(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700351 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800352 destroySessionLocked(session);
353 }
354 }
355
356 void destroySession(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700357 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800358 destroySessionLocked(session);
359 }
360 }
361
RoboErik4646d282014-05-13 10:13:04 -0700362 private void updateUser() {
363 synchronized (mLock) {
Jaewan Kim8f729082016-06-21 12:36:26 +0900364 UserManager manager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Jaewan Kima7dce192017-02-16 17:10:54 +0900365 mFullUserIds.clear();
366 List<UserInfo> allUsers = manager.getUsers();
367 if (allUsers != null) {
368 for (UserInfo userInfo : allUsers) {
369 if (userInfo.isManagedProfile()) {
370 mFullUserIds.put(userInfo.id, userInfo.profileGroupId);
371 } else {
372 mFullUserIds.put(userInfo.id, userInfo.id);
373 if (mUserRecords.get(userInfo.id) == null) {
374 mUserRecords.put(userInfo.id, new FullUserRecord(userInfo.id));
375 }
376 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900377 }
RoboErik4646d282014-05-13 10:13:04 -0700378 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900379 // Ensure that the current full user exists.
380 int currentFullUserId = ActivityManager.getCurrentUser();
381 mCurrentFullUserRecord = mUserRecords.get(currentFullUserId);
382 if (mCurrentFullUserRecord == null) {
383 Log.w(TAG, "Cannot find FullUserInfo for the current user " + currentFullUserId);
384 mCurrentFullUserRecord = new FullUserRecord(currentFullUserId);
385 mUserRecords.put(currentFullUserId, mCurrentFullUserRecord);
386 }
387 mFullUserIds.put(currentFullUserId, currentFullUserId);
RoboErik4646d282014-05-13 10:13:04 -0700388 }
389 }
390
RoboErik7aef77b2014-08-08 15:56:54 -0700391 private void updateActiveSessionListeners() {
392 synchronized (mLock) {
393 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
394 SessionsListenerRecord listener = mSessionsListeners.get(i);
395 try {
396 enforceMediaPermissions(listener.mComponentName, listener.mPid, listener.mUid,
397 listener.mUserId);
398 } catch (SecurityException e) {
399 Log.i(TAG, "ActiveSessionsListener " + listener.mComponentName
400 + " is no longer authorized. Disconnecting.");
401 mSessionsListeners.remove(i);
402 try {
403 listener.mListener
404 .onActiveSessionsChanged(new ArrayList<MediaSession.Token>());
405 } catch (Exception e1) {
406 // ignore
407 }
408 }
409 }
410 }
411 }
412
RoboErik4646d282014-05-13 10:13:04 -0700413 /*
414 * When a session is removed several things need to happen.
415 * 1. We need to remove it from the relevant user.
416 * 2. We need to remove it from the priority stack.
417 * 3. We need to remove it from all sessions.
418 * 4. If this is the system priority session we need to clear it.
419 * 5. We need to unlink to death from the cb binder
420 * 6. We need to tell the session to do any final cleanup (onDestroy)
421 */
RoboErik01fe6612014-02-13 14:19:04 -0800422 private void destroySessionLocked(MediaSessionRecord session) {
Insun Kang30be970a2015-11-26 15:35:44 +0900423 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900424 Log.d(TAG, "Destroying " + session);
Insun Kang30be970a2015-11-26 15:35:44 +0900425 }
Jaewan Kim101b4d52017-05-18 13:23:11 +0900426 FullUserRecord user = getFullUserRecordLocked(session.getUserId());
Jaewan Kima7dce192017-02-16 17:10:54 +0900427 if (mGlobalPrioritySession == session) {
428 mGlobalPrioritySession = null;
Jaewan Kim92dea332017-02-02 11:52:08 +0900429 if (session.isActive() && user != null) {
430 user.pushAddressedPlayerChangedLocked();
431 }
Jaewan Kim101b4d52017-05-18 13:23:11 +0900432 } else {
433 if (user != null) {
434 user.mPriorityStack.removeSession(session);
435 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900436 }
RoboErik4646d282014-05-13 10:13:04 -0700437
438 try {
439 session.getCallback().asBinder().unlinkToDeath(session, 0);
440 } catch (Exception e) {
441 // ignore exceptions while destroying a session.
442 }
443 session.onDestroy();
Jaewan Kim92dea332017-02-02 11:52:08 +0900444 mHandler.postSessionsChanged(session.getUserId());
RoboErik01fe6612014-02-13 14:19:04 -0800445 }
446
Jaewan Kim66d451b2018-02-12 21:23:06 +0900447 private void registerPackageBroadcastReceivers() {
448 // TODO(jaewan): Only consider changed packages when building session service list
449 // when we make this multi-user aware. At that time,
450 // use PackageMonitor.getChangingUserId() to know which user has changed.
Jaewan Kim005e2bb2018-03-02 15:55:12 +0900451 // (b/73597722)
Jaewan Kim66d451b2018-02-12 21:23:06 +0900452 IntentFilter filter = new IntentFilter();
453 filter.addDataScheme("package");
454 filter.addAction(Intent.ACTION_PACKAGE_ADDED);
455 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
456 filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
457 filter.addAction(Intent.ACTION_PACKAGES_SUSPENDED);
458 filter.addAction(Intent.ACTION_PACKAGES_UNSUSPENDED);
459 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
460 filter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
461 filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
462
463 getContext().registerReceiverAsUser(new BroadcastReceiver() {
464 @Override
465 public void onReceive(Context context, Intent intent) {
466 final int changeUserId = intent.getIntExtra(
467 Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
468 if (changeUserId == UserHandle.USER_NULL) {
469 Log.w(TAG, "Intent broadcast does not contain user handle: "+ intent);
470 return;
471 }
472 // Check if the package is replacing (i.e. reinstalling)
473 final boolean isReplacing = intent.getBooleanExtra(Intent.EXTRA_REPLACING, false);
Jaewan Kim005e2bb2018-03-02 15:55:12 +0900474 // TODO(jaewan): Add multi-user support with this. (b/73597722)
Jaewan Kim66d451b2018-02-12 21:23:06 +0900475 // final int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
476
477 if (DEBUG) {
478 Log.d(TAG, "Received change in packages, intent=" + intent);
479 }
480 switch (intent.getAction()) {
481 case Intent.ACTION_PACKAGE_ADDED:
482 case Intent.ACTION_PACKAGE_REMOVED:
483 case Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE:
484 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
485 if (isReplacing) {
486 // Ignore if the package(s) are replacing. In that case, followings will
487 // happen in order.
488 // 1. ACTION_PACKAGE_REMOVED with isReplacing=true
489 // 2. ACTION_PACKAGE_ADDED with isReplacing=true
490 // 3. ACTION_PACKAGE_REPLACED
491 // (Note that ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE and
492 // ACTION_EXTERNAL_APPLICATIONS_AVAILABLE will be also called with
493 // isReplacing=true for both ASEC hosted packages and packages in
494 // external storage)
495 // Since we only want to update session service list once, ignore
496 // actions above when replacing.
497 // Replacing will be handled only once with the ACTION_PACKAGE_REPLACED.
498 break;
499 }
500 // pass-through
501 case Intent.ACTION_PACKAGE_CHANGED:
502 case Intent.ACTION_PACKAGES_SUSPENDED:
503 case Intent.ACTION_PACKAGES_UNSUSPENDED:
504 case Intent.ACTION_PACKAGE_REPLACED:
505 buildMediaSessionService2List();
506 }
507 }
508 }, UserHandle.ALL, filter, null, BackgroundThread.getHandler());
509 }
510
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900511 private void buildMediaSessionService2List() {
Jaewan Kim129a5622018-03-28 12:19:04 +0900512 if (!USE_MEDIA2_APIS) {
513 return;
514 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900515 if (DEBUG) {
516 Log.d(TAG, "buildMediaSessionService2List");
517 }
Jaewan Kim005e2bb2018-03-02 15:55:12 +0900518 // TODO(jaewan): Also query for managed profile users. (b/73597722)
Jaewan Kimf7a77062018-01-27 01:34:24 +0900519 PackageManager manager = getContext().getPackageManager();
Jaewan Kimbcecf312018-01-23 19:30:42 +0900520 List<ResolveInfo> services = new ArrayList<>();
521 // If multiple actions are declared for a service, browser gets higher priority.
Jaewan Kimf7a77062018-01-27 01:34:24 +0900522 List<ResolveInfo> libraryServices = manager.queryIntentServices(
Jaewan Kimbcecf312018-01-23 19:30:42 +0900523 new Intent(MediaLibraryService2.SERVICE_INTERFACE), PackageManager.GET_META_DATA);
524 if (libraryServices != null) {
525 services.addAll(libraryServices);
526 }
Jaewan Kimf7a77062018-01-27 01:34:24 +0900527 List<ResolveInfo> sessionServices = manager.queryIntentServices(
Jaewan Kimbcecf312018-01-23 19:30:42 +0900528 new Intent(MediaSessionService2.SERVICE_INTERFACE), PackageManager.GET_META_DATA);
529 if (sessionServices != null) {
530 services.addAll(sessionServices);
531 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900532 synchronized (mLock) {
Jaewan Kim66d451b2018-02-12 21:23:06 +0900533 // List to keep the session services that need be removed because they don't exist
534 // in the 'services' above.
Sungsoo Lim375efa12018-03-02 10:17:08 +0900535 boolean notifySessionTokensUpdated = false;
Sungsoo Limc0d54a22018-02-27 09:05:21 +0900536 Set<SessionToken2> sessionTokensToRemove = new HashSet<>();
537 for (SessionToken2 token : mSessionRecords.keySet()) {
538 if (token.getType() != TYPE_SESSION) {
539 sessionTokensToRemove.add(token);
Jaewan Kim66d451b2018-02-12 21:23:06 +0900540 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900541 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900542
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900543 for (int i = 0; i < services.size(); i++) {
544 if (services.get(i) == null || services.get(i).serviceInfo == null) {
545 continue;
546 }
547 ServiceInfo serviceInfo = services.get(i).serviceInfo;
Jaewan Kimf7a77062018-01-27 01:34:24 +0900548 int uid;
549 try {
Jaewan Kim005e2bb2018-03-02 15:55:12 +0900550 // TODO(jaewan): Do this per user. (b/73597722)
Jaewan Kimf7a77062018-01-27 01:34:24 +0900551 uid = manager.getPackageUid(serviceInfo.packageName,
552 PackageManager.GET_META_DATA);
553 } catch (NameNotFoundException e) {
554 continue;
555 }
Jaewan Kim66d451b2018-02-12 21:23:06 +0900556 SessionToken2 token;
Jaewan Kim44fec2d2018-01-29 21:49:41 +0900557 try {
Jaewan Kim66d451b2018-02-12 21:23:06 +0900558 token = new SessionToken2(getContext(),
Jaewan Kim44fec2d2018-01-29 21:49:41 +0900559 serviceInfo.packageName, serviceInfo.name, uid);
Jaewan Kim66d451b2018-02-12 21:23:06 +0900560 } catch (IllegalArgumentException e) {
561 Log.w(TAG, "Invalid session service", e);
562 continue;
563 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900564 // If the token already exists, keep it in the mSessions by removing from
565 // sessionTokensToRemove.
566 if (!sessionTokensToRemove.remove(token)) {
Jaewan Kim66d451b2018-02-12 21:23:06 +0900567 // New session service is found.
Sungsoo Lim375efa12018-03-02 10:17:08 +0900568 notifySessionTokensUpdated |= addSessionRecordLocked(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900569 }
570 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900571 for (SessionToken2 token : sessionTokensToRemove) {
572 mSessionRecords.remove(token);
Sungsoo Lim375efa12018-03-02 10:17:08 +0900573 notifySessionTokensUpdated |= removeSessionRecordLocked(token);
574 }
575
576 if (notifySessionTokensUpdated) {
577 // TODO(jaewan): Pass proper user id to postSessionTokensUpdated(...)
578 postSessionTokensUpdated(UserHandle.USER_ALL);
Jaewan Kim66d451b2018-02-12 21:23:06 +0900579 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900580 }
581 if (DEBUG) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900582 Log.d(TAG, "Found " + mSessionRecords.size() + " session services");
583 for (SessionToken2 token : mSessionRecords.keySet()) {
584 Log.d(TAG, " " + token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900585 }
586 }
587 }
588
RoboErik01fe6612014-02-13 14:19:04 -0800589 private void enforcePackageName(String packageName, int uid) {
590 if (TextUtils.isEmpty(packageName)) {
591 throw new IllegalArgumentException("packageName may not be empty");
592 }
593 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
594 final int packageCount = packages.length;
595 for (int i = 0; i < packageCount; i++) {
596 if (packageName.equals(packages[i])) {
597 return;
598 }
599 }
600 throw new IllegalArgumentException("packageName is not owned by the calling process");
601 }
602
RoboErike7880d82014-04-30 12:48:25 -0700603 /**
604 * Checks a caller's authorization to register an IRemoteControlDisplay.
605 * Authorization is granted if one of the following is true:
606 * <ul>
607 * <li>the caller has android.Manifest.permission.MEDIA_CONTENT_CONTROL
608 * permission</li>
RoboErika5b02322014-05-07 17:05:49 -0700609 * <li>the caller's listener is one of the enabled notification listeners
610 * for the caller's user</li>
RoboErike7880d82014-04-30 12:48:25 -0700611 * </ul>
612 */
RoboErika5b02322014-05-07 17:05:49 -0700613 private void enforceMediaPermissions(ComponentName compName, int pid, int uid,
614 int resolvedUserId) {
Hyundo Moonf84c1c02018-03-19 20:33:27 +0900615 if (isCurrentVolumeController(pid, uid)) return;
RoboErike7880d82014-04-30 12:48:25 -0700616 if (getContext()
617 .checkPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
618 != PackageManager.PERMISSION_GRANTED
RoboErika5b02322014-05-07 17:05:49 -0700619 && !isEnabledNotificationListener(compName, UserHandle.getUserId(uid),
620 resolvedUserId)) {
RoboErike7880d82014-04-30 12:48:25 -0700621 throw new SecurityException("Missing permission to control media.");
622 }
623 }
624
Hyundo Moonf84c1c02018-03-19 20:33:27 +0900625 private boolean isCurrentVolumeController(int pid, int uid) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500626 return getContext().checkPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
627 pid, uid) == PackageManager.PERMISSION_GRANTED;
John Spurlockbe19ed02015-02-22 10:57:55 -0500628 }
629
630 private void enforceSystemUiPermission(String action, int pid, int uid) {
Hyundo Moonf84c1c02018-03-19 20:33:27 +0900631 if (!isCurrentVolumeController(pid, uid)) {
RoboErik19c95182014-06-23 15:38:48 -0700632 throw new SecurityException("Only system ui may " + action);
633 }
634 }
635
RoboErika5b02322014-05-07 17:05:49 -0700636 /**
637 * This checks if the component is an enabled notification listener for the
638 * specified user. Enabled components may only operate on behalf of the user
639 * they're running as.
640 *
641 * @param compName The component that is enabled.
642 * @param userId The user id of the caller.
643 * @param forUserId The user id they're making the request on behalf of.
644 * @return True if the component is enabled, false otherwise
645 */
646 private boolean isEnabledNotificationListener(ComponentName compName, int userId,
647 int forUserId) {
648 if (userId != forUserId) {
649 // You may not access another user's content as an enabled listener.
650 return false;
651 }
RoboErik51fa6bc2014-06-20 14:59:58 -0700652 if (DEBUG) {
653 Log.d(TAG, "Checking if enabled notification listener " + compName);
654 }
RoboErike7880d82014-04-30 12:48:25 -0700655 if (compName != null) {
Julia Reynoldsb852e562017-06-06 16:14:18 -0400656 try {
657 return mNotificationManager.isNotificationListenerAccessGrantedForUser(
658 compName, userId);
659 } catch(RemoteException e) {
660 Log.w(TAG, "Dead NotificationManager in isEnabledNotificationListener", e);
RoboErike7880d82014-04-30 12:48:25 -0700661 }
662 }
663 return false;
664 }
665
RoboErika5b02322014-05-07 17:05:49 -0700666 private MediaSessionRecord createSessionInternal(int callerPid, int callerUid, int userId,
RoboErik4646d282014-05-13 10:13:04 -0700667 String callerPackageName, ISessionCallback cb, String tag) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800668 synchronized (mLock) {
RoboErika5b02322014-05-07 17:05:49 -0700669 return createSessionLocked(callerPid, callerUid, userId, callerPackageName, cb, tag);
RoboErik01fe6612014-02-13 14:19:04 -0800670 }
671 }
672
RoboErik4646d282014-05-13 10:13:04 -0700673 /*
674 * When a session is created the following things need to happen.
RoboErik8a2cfc32014-05-16 11:19:38 -0700675 * 1. Its callback binder needs a link to death
RoboErik4646d282014-05-13 10:13:04 -0700676 * 2. It needs to be added to all sessions.
677 * 3. It needs to be added to the priority stack.
678 * 4. It needs to be added to the relevant user record.
679 */
RoboErika5b02322014-05-07 17:05:49 -0700680 private MediaSessionRecord createSessionLocked(int callerPid, int callerUid, int userId,
681 String callerPackageName, ISessionCallback cb, String tag) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900682 FullUserRecord user = getFullUserRecordLocked(userId);
Dongwon Kang8cf39c52016-07-29 13:20:39 -0700683 if (user == null) {
684 Log.wtf(TAG, "Request from invalid user: " + userId);
685 throw new RuntimeException("Session request from invalid user.");
686 }
687
RoboErika5b02322014-05-07 17:05:49 -0700688 final MediaSessionRecord session = new MediaSessionRecord(callerPid, callerUid, userId,
Jaewan Kim92dea332017-02-02 11:52:08 +0900689 callerPackageName, cb, tag, this, mHandler.getLooper());
RoboErik01fe6612014-02-13 14:19:04 -0800690 try {
691 cb.asBinder().linkToDeath(session, 0);
692 } catch (RemoteException e) {
693 throw new RuntimeException("Media Session owner died prematurely.", e);
694 }
RoboErik4646d282014-05-13 10:13:04 -0700695
Jaewan Kim101b4d52017-05-18 13:23:11 +0900696 user.mPriorityStack.addSession(session);
Jaewan Kim92dea332017-02-02 11:52:08 +0900697 mHandler.postSessionsChanged(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700698
RoboErik01fe6612014-02-13 14:19:04 -0800699 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900700 Log.d(TAG, "Created session for " + callerPackageName + " with tag " + tag);
RoboErik01fe6612014-02-13 14:19:04 -0800701 }
702 return session;
703 }
704
RoboErik2e7a9162014-06-04 16:53:45 -0700705 private int findIndexOfSessionsListenerLocked(IActiveSessionsListener listener) {
706 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
RoboErika08adb242014-11-21 18:28:18 -0800707 if (mSessionsListeners.get(i).mListener.asBinder() == listener.asBinder()) {
RoboErik2e7a9162014-06-04 16:53:45 -0700708 return i;
709 }
710 }
711 return -1;
712 }
713
RoboErik2e7a9162014-06-04 16:53:45 -0700714 private void pushSessionsChanged(int userId) {
715 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900716 FullUserRecord user = getFullUserRecordLocked(userId);
717 if (user == null) {
718 Log.w(TAG, "pushSessionsChanged failed. No user with id=" + userId);
719 return;
720 }
Jaewan Kim101b4d52017-05-18 13:23:11 +0900721 List<MediaSessionRecord> records = getActiveSessionsLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700722 int size = records.size();
Jeff Browndba34ba2014-06-24 20:46:03 -0700723 ArrayList<MediaSession.Token> tokens = new ArrayList<MediaSession.Token>();
RoboErik2e7a9162014-06-04 16:53:45 -0700724 for (int i = 0; i < size; i++) {
Jeff Browndba34ba2014-06-24 20:46:03 -0700725 tokens.add(new MediaSession.Token(records.get(i).getControllerBinder()));
RoboErik2e7a9162014-06-04 16:53:45 -0700726 }
RoboErik19c95182014-06-23 15:38:48 -0700727 pushRemoteVolumeUpdateLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700728 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
729 SessionsListenerRecord record = mSessionsListeners.get(i);
730 if (record.mUserId == UserHandle.USER_ALL || record.mUserId == userId) {
731 try {
732 record.mListener.onActiveSessionsChanged(tokens);
733 } catch (RemoteException e) {
734 Log.w(TAG, "Dead ActiveSessionsListener in pushSessionsChanged, removing",
735 e);
736 mSessionsListeners.remove(i);
737 }
738 }
739 }
740 }
741 }
742
RoboErik19c95182014-06-23 15:38:48 -0700743 private void pushRemoteVolumeUpdateLocked(int userId) {
744 if (mRvc != null) {
745 try {
Jaewan Kima7dce192017-02-16 17:10:54 +0900746 FullUserRecord user = getFullUserRecordLocked(userId);
747 if (user == null) {
748 Log.w(TAG, "pushRemoteVolumeUpdateLocked failed. No user with id=" + userId);
749 return;
750 }
751 MediaSessionRecord record = user.mPriorityStack.getDefaultRemoteSession(userId);
RoboErik19c95182014-06-23 15:38:48 -0700752 mRvc.updateRemoteController(record == null ? null : record.getControllerBinder());
753 } catch (RemoteException e) {
754 Log.wtf(TAG, "Error sending default remote volume to sys ui.", e);
755 }
756 }
757 }
758
Jaewan Kim92dea332017-02-02 11:52:08 +0900759 /**
760 * Called when the media button receiver for the {@param record} is changed.
761 *
762 * @param record the media session whose media button receiver is updated.
763 */
764 public void onMediaButtonReceiverChanged(MediaSessionRecord record) {
765 synchronized (mLock) {
766 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
767 MediaSessionRecord mediaButtonSession =
768 user.mPriorityStack.getMediaButtonSession();
769 if (record == mediaButtonSession) {
770 user.rememberMediaButtonReceiverLocked(mediaButtonSession);
771 }
772 }
773 }
774
Jaewan Kim50269362016-12-23 11:22:02 +0900775 private String getCallingPackageName(int uid) {
776 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
777 if (packages != null && packages.length > 0) {
778 return packages[0];
779 }
780 return "";
781 }
782
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900783 private void dispatchVolumeKeyLongPressLocked(KeyEvent keyEvent) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900784 try {
Jaewan Kima7dce192017-02-16 17:10:54 +0900785 mCurrentFullUserRecord.mOnVolumeKeyLongPressListener.onVolumeKeyLongPress(keyEvent);
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900786 } catch (RemoteException e) {
787 Log.w(TAG, "Failed to send " + keyEvent + " to volume key long-press listener");
788 }
789 }
790
Jaewan Kima7dce192017-02-16 17:10:54 +0900791 private FullUserRecord getFullUserRecordLocked(int userId) {
792 int fullUserId = mFullUserIds.get(userId, -1);
793 if (fullUserId < 0) {
794 return null;
795 }
796 return mUserRecords.get(fullUserId);
797 }
798
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900799 void destroySession2Internal(SessionToken2 token) {
800 synchronized (mLock) {
Sungsoo Lim375efa12018-03-02 10:17:08 +0900801 boolean notifySessionTokensUpdated = false;
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900802 if (token.getType() == SessionToken2.TYPE_SESSION) {
Sungsoo Lim375efa12018-03-02 10:17:08 +0900803 notifySessionTokensUpdated |= removeSessionRecordLocked(token);
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900804 } else {
Sungsoo Lim375efa12018-03-02 10:17:08 +0900805 notifySessionTokensUpdated |= addSessionRecordLocked(token);
806 }
807 if (notifySessionTokensUpdated) {
808 postSessionTokensUpdated(UserHandle.getUserId(token.getUid()));
Sungsoo Lim117c7f72018-02-13 16:02:24 +0900809 }
810 }
811 }
812
RoboErik4646d282014-05-13 10:13:04 -0700813 /**
Jaewan Kima7dce192017-02-16 17:10:54 +0900814 * Information about a full user and its corresponding managed profiles.
815 *
816 * <p>Since the full user runs together with its managed profiles, a user wouldn't differentiate
817 * them when he/she presses a media/volume button. So keeping media sessions for them in one
818 * place makes more sense and increases the readability.</p>
819 * <p>The contents of this object is guarded by {@link #mLock}.
RoboErik4646d282014-05-13 10:13:04 -0700820 */
Jaewan Kim92dea332017-02-02 11:52:08 +0900821 final class FullUserRecord implements MediaSessionStack.OnMediaButtonSessionChangedListener {
Jaewan Kima7dce192017-02-16 17:10:54 +0900822 private static final String COMPONENT_NAME_USER_ID_DELIM = ",";
823 private final int mFullUserId;
Jaewan Kim92dea332017-02-02 11:52:08 +0900824 private final MediaSessionStack mPriorityStack;
RoboErikb214efb2014-07-24 13:20:30 -0700825 private PendingIntent mLastMediaButtonReceiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800826 private ComponentName mRestoredMediaButtonReceiver;
Jaewan Kima7dce192017-02-16 17:10:54 +0900827 private int mRestoredMediaButtonReceiverUserId;
RoboErik4646d282014-05-13 10:13:04 -0700828
Jaewan Kim50269362016-12-23 11:22:02 +0900829 private IOnVolumeKeyLongPressListener mOnVolumeKeyLongPressListener;
830 private int mOnVolumeKeyLongPressListenerUid;
831 private KeyEvent mInitialDownVolumeKeyEvent;
832 private int mInitialDownVolumeStream;
833 private boolean mInitialDownMusicOnly;
834
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800835 private IOnMediaKeyListener mOnMediaKeyListener;
836 private int mOnMediaKeyListenerUid;
Jaewan Kima7dce192017-02-16 17:10:54 +0900837 private ICallback mCallback;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800838
Jaewan Kima7dce192017-02-16 17:10:54 +0900839 public FullUserRecord(int fullUserId) {
840 mFullUserId = fullUserId;
Sungsoo Lim875e6972017-11-03 02:22:35 +0000841 mPriorityStack = new MediaSessionStack(mAudioPlayerStateMonitor, this);
Jaewan Kima7dce192017-02-16 17:10:54 +0900842 // Restore the remembered media button receiver before the boot.
843 String mediaButtonReceiver = Settings.Secure.getStringForUser(mContentResolver,
844 Settings.System.MEDIA_BUTTON_RECEIVER, mFullUserId);
845 if (mediaButtonReceiver == null) {
846 return;
847 }
848 String[] tokens = mediaButtonReceiver.split(COMPONENT_NAME_USER_ID_DELIM);
849 if (tokens == null || tokens.length != 2) {
850 return;
851 }
852 mRestoredMediaButtonReceiver = ComponentName.unflattenFromString(tokens[0]);
853 mRestoredMediaButtonReceiverUserId = Integer.parseInt(tokens[1]);
RoboErik4646d282014-05-13 10:13:04 -0700854 }
855
Jaewan Kima7dce192017-02-16 17:10:54 +0900856 public void destroySessionsForUserLocked(int userId) {
Jaewan Kim92dea332017-02-02 11:52:08 +0900857 List<MediaSessionRecord> sessions = mPriorityStack.getPriorityList(false, userId);
Jaewan Kima7dce192017-02-16 17:10:54 +0900858 for (MediaSessionRecord session : sessions) {
RoboErik4646d282014-05-13 10:13:04 -0700859 MediaSessionService.this.destroySessionLocked(session);
RoboErik4646d282014-05-13 10:13:04 -0700860 }
861 }
862
RoboErik4646d282014-05-13 10:13:04 -0700863 public void dumpLocked(PrintWriter pw, String prefix) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900864 pw.print(prefix + "Record for full_user=" + mFullUserId);
865 // Dump managed profile user ids associated with this user.
866 int size = mFullUserIds.size();
867 for (int i = 0; i < size; i++) {
868 if (mFullUserIds.keyAt(i) != mFullUserIds.valueAt(i)
869 && mFullUserIds.valueAt(i) == mFullUserId) {
870 pw.print(", profile_user=" + mFullUserIds.keyAt(i));
871 }
872 }
873 pw.println();
RoboErik4646d282014-05-13 10:13:04 -0700874 String indent = prefix + " ";
Jaewan Kima7dce192017-02-16 17:10:54 +0900875 pw.println(indent + "Volume key long-press listener: " + mOnVolumeKeyLongPressListener);
876 pw.println(indent + "Volume key long-press listener package: " +
Jaewan Kim50269362016-12-23 11:22:02 +0900877 getCallingPackageName(mOnVolumeKeyLongPressListenerUid));
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800878 pw.println(indent + "Media key listener: " + mOnMediaKeyListener);
879 pw.println(indent + "Media key listener package: " +
880 getCallingPackageName(mOnMediaKeyListenerUid));
Jaewan Kima7dce192017-02-16 17:10:54 +0900881 pw.println(indent + "Callback: " + mCallback);
882 pw.println(indent + "Last MediaButtonReceiver: " + mLastMediaButtonReceiver);
883 pw.println(indent + "Restored MediaButtonReceiver: " + mRestoredMediaButtonReceiver);
884 mPriorityStack.dump(pw, indent);
885 }
886
Jaewan Kim92dea332017-02-02 11:52:08 +0900887 @Override
888 public void onMediaButtonSessionChanged(MediaSessionRecord oldMediaButtonSession,
889 MediaSessionRecord newMediaButtonSession) {
890 if (DEBUG_KEY_EVENT) {
Jaewan Kim98e4aaf2017-05-12 17:06:47 +0900891 Log.d(TAG, "Media button session is changed to " + newMediaButtonSession);
Jaewan Kim92dea332017-02-02 11:52:08 +0900892 }
893 synchronized (mLock) {
894 if (oldMediaButtonSession != null) {
895 mHandler.postSessionsChanged(oldMediaButtonSession.getUserId());
896 }
897 if (newMediaButtonSession != null) {
898 rememberMediaButtonReceiverLocked(newMediaButtonSession);
899 mHandler.postSessionsChanged(newMediaButtonSession.getUserId());
900 }
901 pushAddressedPlayerChangedLocked();
902 }
903 }
904
905 // Remember media button receiver and keep it in the persistent storage.
906 public void rememberMediaButtonReceiverLocked(MediaSessionRecord record) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900907 PendingIntent receiver = record.getMediaButtonReceiver();
Jaewan Kima7dce192017-02-16 17:10:54 +0900908 mLastMediaButtonReceiver = receiver;
Jaewan Kim92dea332017-02-02 11:52:08 +0900909 mRestoredMediaButtonReceiver = null;
910 String componentName = "";
911 if (receiver != null) {
912 ComponentName component = receiver.getIntent().getComponent();
913 if (component != null
914 && record.getPackageName().equals(component.getPackageName())) {
915 componentName = component.flattenToString();
916 }
RoboErik4646d282014-05-13 10:13:04 -0700917 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900918 Settings.Secure.putStringForUser(mContentResolver,
919 Settings.System.MEDIA_BUTTON_RECEIVER,
920 componentName + COMPONENT_NAME_USER_ID_DELIM + record.getUserId(),
921 mFullUserId);
RoboErik4646d282014-05-13 10:13:04 -0700922 }
RoboErikc8f92d12015-01-05 16:48:07 -0800923
Jaewan Kima7dce192017-02-16 17:10:54 +0900924 private void pushAddressedPlayerChangedLocked() {
925 if (mCallback == null) {
926 return;
RoboErikc8f92d12015-01-05 16:48:07 -0800927 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900928 try {
929 MediaSessionRecord mediaButtonSession = getMediaButtonSessionLocked();
930 if (mediaButtonSession != null) {
931 mCallback.onAddressedPlayerChangedToMediaSession(
932 new MediaSession.Token(mediaButtonSession.getControllerBinder()));
933 } else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
934 mCallback.onAddressedPlayerChangedToMediaButtonReceiver(
935 mCurrentFullUserRecord.mLastMediaButtonReceiver
936 .getIntent().getComponent());
937 } else if (mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
938 mCallback.onAddressedPlayerChangedToMediaButtonReceiver(
939 mCurrentFullUserRecord.mRestoredMediaButtonReceiver);
940 }
941 } catch (RemoteException e) {
942 Log.w(TAG, "Failed to pushAddressedPlayerChangedLocked", e);
943 }
944 }
945
946 private MediaSessionRecord getMediaButtonSessionLocked() {
Jaewan Kim92dea332017-02-02 11:52:08 +0900947 return isGlobalPriorityActiveLocked()
948 ? mGlobalPrioritySession : mPriorityStack.getMediaButtonSession();
RoboErikc8f92d12015-01-05 16:48:07 -0800949 }
RoboErik4646d282014-05-13 10:13:04 -0700950 }
951
RoboErik2e7a9162014-06-04 16:53:45 -0700952 final class SessionsListenerRecord implements IBinder.DeathRecipient {
953 private final IActiveSessionsListener mListener;
RoboErik7aef77b2014-08-08 15:56:54 -0700954 private final ComponentName mComponentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700955 private final int mUserId;
RoboErik7aef77b2014-08-08 15:56:54 -0700956 private final int mPid;
957 private final int mUid;
RoboErik2e7a9162014-06-04 16:53:45 -0700958
RoboErik7aef77b2014-08-08 15:56:54 -0700959 public SessionsListenerRecord(IActiveSessionsListener listener,
960 ComponentName componentName,
961 int userId, int pid, int uid) {
RoboErik2e7a9162014-06-04 16:53:45 -0700962 mListener = listener;
RoboErik7aef77b2014-08-08 15:56:54 -0700963 mComponentName = componentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700964 mUserId = userId;
RoboErik7aef77b2014-08-08 15:56:54 -0700965 mPid = pid;
966 mUid = uid;
RoboErik2e7a9162014-06-04 16:53:45 -0700967 }
968
969 @Override
970 public void binderDied() {
971 synchronized (mLock) {
972 mSessionsListeners.remove(this);
973 }
974 }
975 }
976
RoboErik7aef77b2014-08-08 15:56:54 -0700977 final class SettingsObserver extends ContentObserver {
978 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(
979 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
980
981 private SettingsObserver() {
982 super(null);
983 }
984
985 private void observe() {
986 mContentResolver.registerContentObserver(mSecureSettingsUri,
987 false, this, UserHandle.USER_ALL);
988 }
989
990 @Override
991 public void onChange(boolean selfChange, Uri uri) {
992 updateActiveSessionListeners();
993 }
994 }
995
RoboErik07c70772014-03-20 13:33:52 -0700996 class SessionManagerImpl extends ISessionManager.Stub {
RoboErik8a2cfc32014-05-16 11:19:38 -0700997 private static final String EXTRA_WAKELOCK_ACQUIRED =
998 "android.media.AudioService.WAKELOCK_ACQUIRED";
999 private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; // magic number
1000
RoboErik9a9d0b52014-05-20 14:53:39 -07001001 private boolean mVoiceButtonDown = false;
1002 private boolean mVoiceButtonHandled = false;
1003
RoboErik07c70772014-03-20 13:33:52 -07001004 @Override
RoboErika5b02322014-05-07 17:05:49 -07001005 public ISession createSession(String packageName, ISessionCallback cb, String tag,
1006 int userId) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -08001007 final int pid = Binder.getCallingPid();
1008 final int uid = Binder.getCallingUid();
1009 final long token = Binder.clearCallingIdentity();
1010 try {
1011 enforcePackageName(packageName, uid);
RoboErika5b02322014-05-07 17:05:49 -07001012 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
1013 false /* allowAll */, true /* requireFull */, "createSession", packageName);
RoboErik01fe6612014-02-13 14:19:04 -08001014 if (cb == null) {
1015 throw new IllegalArgumentException("Controller callback cannot be null");
1016 }
RoboErika5b02322014-05-07 17:05:49 -07001017 return createSessionInternal(pid, uid, resolvedUserId, packageName, cb, tag)
1018 .getSessionBinder();
RoboErike7880d82014-04-30 12:48:25 -07001019 } finally {
1020 Binder.restoreCallingIdentity(token);
1021 }
1022 }
1023
1024 @Override
RoboErika5b02322014-05-07 17:05:49 -07001025 public List<IBinder> getSessions(ComponentName componentName, int userId) {
RoboErike7880d82014-04-30 12:48:25 -07001026 final int pid = Binder.getCallingPid();
1027 final int uid = Binder.getCallingUid();
1028 final long token = Binder.clearCallingIdentity();
1029
1030 try {
RoboErik2e7a9162014-06-04 16:53:45 -07001031 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
RoboErike7880d82014-04-30 12:48:25 -07001032 ArrayList<IBinder> binders = new ArrayList<IBinder>();
1033 synchronized (mLock) {
Jaewan Kim101b4d52017-05-18 13:23:11 +09001034 List<MediaSessionRecord> records = getActiveSessionsLocked(resolvedUserId);
1035 for (MediaSessionRecord record : records) {
1036 binders.add(record.getControllerBinder().asBinder());
RoboErike7880d82014-04-30 12:48:25 -07001037 }
1038 }
1039 return binders;
RoboErik01fe6612014-02-13 14:19:04 -08001040 } finally {
1041 Binder.restoreCallingIdentity(token);
1042 }
1043 }
RoboErika278ea72014-04-24 14:49:01 -07001044
RoboErik2e7a9162014-06-04 16:53:45 -07001045 @Override
1046 public void addSessionsListener(IActiveSessionsListener listener,
1047 ComponentName componentName, int userId) throws RemoteException {
1048 final int pid = Binder.getCallingPid();
1049 final int uid = Binder.getCallingUid();
1050 final long token = Binder.clearCallingIdentity();
1051
1052 try {
1053 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
1054 synchronized (mLock) {
1055 int index = findIndexOfSessionsListenerLocked(listener);
1056 if (index != -1) {
1057 Log.w(TAG, "ActiveSessionsListener is already added, ignoring");
1058 return;
1059 }
1060 SessionsListenerRecord record = new SessionsListenerRecord(listener,
RoboErik7aef77b2014-08-08 15:56:54 -07001061 componentName, resolvedUserId, pid, uid);
RoboErik2e7a9162014-06-04 16:53:45 -07001062 try {
1063 listener.asBinder().linkToDeath(record, 0);
1064 } catch (RemoteException e) {
1065 Log.e(TAG, "ActiveSessionsListener is dead, ignoring it", e);
1066 return;
1067 }
1068 mSessionsListeners.add(record);
1069 }
1070 } finally {
1071 Binder.restoreCallingIdentity(token);
1072 }
1073 }
1074
1075 @Override
1076 public void removeSessionsListener(IActiveSessionsListener listener)
1077 throws RemoteException {
1078 synchronized (mLock) {
1079 int index = findIndexOfSessionsListenerLocked(listener);
1080 if (index != -1) {
1081 SessionsListenerRecord record = mSessionsListeners.remove(index);
1082 try {
1083 record.mListener.asBinder().unlinkToDeath(record, 0);
1084 } catch (Exception e) {
1085 // ignore exceptions, the record is being removed
1086 }
1087 }
1088 }
1089 }
1090
RoboErik8a2cfc32014-05-16 11:19:38 -07001091 /**
1092 * Handles the dispatching of the media button events to one of the
1093 * registered listeners, or if there was none, broadcast an
1094 * ACTION_MEDIA_BUTTON intent to the rest of the system.
1095 *
1096 * @param keyEvent a non-null KeyEvent whose key code is one of the
1097 * supported media buttons
1098 * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held
1099 * while this key event is dispatched.
1100 */
1101 @Override
1102 public void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
1103 if (keyEvent == null || !KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
1104 Log.w(TAG, "Attempted to dispatch null or non-media key event.");
1105 return;
1106 }
Jeff Brown38d3feb2015-03-19 18:26:30 -07001107
RoboErik8a2cfc32014-05-16 11:19:38 -07001108 final int pid = Binder.getCallingPid();
1109 final int uid = Binder.getCallingUid();
1110 final long token = Binder.clearCallingIdentity();
RoboErik8a2cfc32014-05-16 11:19:38 -07001111 try {
Jeff Brown221a8272015-03-23 13:53:09 -07001112 if (DEBUG) {
1113 Log.d(TAG, "dispatchMediaKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
1114 + keyEvent);
1115 }
Jeff Brown38d3feb2015-03-19 18:26:30 -07001116 if (!isUserSetupComplete()) {
1117 // Global media key handling can have the side-effect of starting new
1118 // activities which is undesirable while setup is in progress.
1119 Slog.i(TAG, "Not dispatching media key event because user "
1120 + "setup is in progress.");
1121 return;
1122 }
1123
RoboErik8a2cfc32014-05-16 11:19:38 -07001124 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001125 boolean isGlobalPriorityActive = isGlobalPriorityActiveLocked();
Jaewan Kim51255012017-02-24 16:19:14 +09001126 if (isGlobalPriorityActive && uid != Process.SYSTEM_UID) {
1127 // Prevent dispatching key event through reflection while the global
1128 // priority session is active.
1129 Slog.i(TAG, "Only the system can dispatch media key event "
1130 + "to the global priority session.");
1131 return;
1132 }
Jaewan Kim98003d32017-02-24 18:33:04 +09001133 if (!isGlobalPriorityActive) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001134 if (mCurrentFullUserRecord.mOnMediaKeyListener != null) {
Jaewan Kim98003d32017-02-24 18:33:04 +09001135 if (DEBUG_KEY_EVENT) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001136 Log.d(TAG, "Send " + keyEvent + " to the media key listener");
Jaewan Kim98003d32017-02-24 18:33:04 +09001137 }
1138 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001139 mCurrentFullUserRecord.mOnMediaKeyListener.onMediaKey(keyEvent,
Jaewan Kim98003d32017-02-24 18:33:04 +09001140 new MediaKeyListenerResultReceiver(keyEvent, needWakeLock));
1141 return;
1142 } catch (RemoteException e) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001143 Log.w(TAG, "Failed to send " + keyEvent
1144 + " to the media key listener");
Jaewan Kim98003d32017-02-24 18:33:04 +09001145 }
1146 }
1147 }
Jaewan Kim51255012017-02-24 16:19:14 +09001148 if (!isGlobalPriorityActive && isVoiceKey(keyEvent.getKeyCode())) {
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001149 handleVoiceKeyEventLocked(keyEvent, needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -07001150 } else {
Jaewan Kim98003d32017-02-24 18:33:04 +09001151 dispatchMediaKeyEventLocked(keyEvent, needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -07001152 }
1153 }
1154 } finally {
1155 Binder.restoreCallingIdentity(token);
1156 }
1157 }
1158
RoboErika278ea72014-04-24 14:49:01 -07001159 @Override
Jaewan Kimbd16f452017-02-03 16:21:38 +09001160 public void setCallback(ICallback callback) {
1161 final int pid = Binder.getCallingPid();
1162 final int uid = Binder.getCallingUid();
1163 final long token = Binder.clearCallingIdentity();
1164 try {
Amith Yamasanie259ad22017-04-24 11:30:19 -07001165 if (!UserHandle.isSameApp(uid, Process.BLUETOOTH_UID)) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001166 throw new SecurityException("Only Bluetooth service processes can set"
1167 + " Callback");
1168 }
1169 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001170 int userId = UserHandle.getUserId(uid);
1171 FullUserRecord user = getFullUserRecordLocked(userId);
1172 if (user == null || user.mFullUserId != userId) {
1173 Log.w(TAG, "Only the full user can set the callback"
1174 + ", userId=" + userId);
1175 return;
1176 }
1177 user.mCallback = callback;
1178 Log.d(TAG, "The callback " + user.mCallback
Jaewan Kimbd16f452017-02-03 16:21:38 +09001179 + " is set by " + getCallingPackageName(uid));
Jaewan Kima7dce192017-02-16 17:10:54 +09001180 if (user.mCallback == null) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001181 return;
1182 }
1183 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001184 user.mCallback.asBinder().linkToDeath(
Jaewan Kimbd16f452017-02-03 16:21:38 +09001185 new IBinder.DeathRecipient() {
1186 @Override
1187 public void binderDied() {
1188 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001189 user.mCallback = null;
Jaewan Kimbd16f452017-02-03 16:21:38 +09001190 }
1191 }
1192 }, 0);
Jaewan Kima7dce192017-02-16 17:10:54 +09001193 user.pushAddressedPlayerChangedLocked();
Jaewan Kimbd16f452017-02-03 16:21:38 +09001194 } catch (RemoteException e) {
1195 Log.w(TAG, "Failed to set callback", e);
Jaewan Kima7dce192017-02-16 17:10:54 +09001196 user.mCallback = null;
Jaewan Kimbd16f452017-02-03 16:21:38 +09001197 }
1198 }
1199 } finally {
1200 Binder.restoreCallingIdentity(token);
1201 }
1202 }
1203
1204 @Override
Jaewan Kim50269362016-12-23 11:22:02 +09001205 public void setOnVolumeKeyLongPressListener(IOnVolumeKeyLongPressListener listener) {
1206 final int pid = Binder.getCallingPid();
1207 final int uid = Binder.getCallingUid();
1208 final long token = Binder.clearCallingIdentity();
1209 try {
1210 // Enforce SET_VOLUME_KEY_LONG_PRESS_LISTENER permission.
1211 if (getContext().checkPermission(
1212 android.Manifest.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER, pid, uid)
1213 != PackageManager.PERMISSION_GRANTED) {
1214 throw new SecurityException("Must hold the SET_VOLUME_KEY_LONG_PRESS_LISTENER" +
1215 " permission.");
1216 }
1217
1218 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001219 int userId = UserHandle.getUserId(uid);
1220 FullUserRecord user = getFullUserRecordLocked(userId);
1221 if (user == null || user.mFullUserId != userId) {
1222 Log.w(TAG, "Only the full user can set the volume key long-press listener"
1223 + ", userId=" + userId);
1224 return;
1225 }
Jaewan Kim50269362016-12-23 11:22:02 +09001226 if (user.mOnVolumeKeyLongPressListener != null &&
1227 user.mOnVolumeKeyLongPressListenerUid != uid) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001228 Log.w(TAG, "The volume key long-press listener cannot be reset"
1229 + " by another app , mOnVolumeKeyLongPressListener="
1230 + user.mOnVolumeKeyLongPressListenerUid
1231 + ", uid=" + uid);
Jaewan Kim50269362016-12-23 11:22:02 +09001232 return;
1233 }
1234
1235 user.mOnVolumeKeyLongPressListener = listener;
1236 user.mOnVolumeKeyLongPressListenerUid = uid;
1237
Jaewan Kima7dce192017-02-16 17:10:54 +09001238 Log.d(TAG, "The volume key long-press listener "
Jaewan Kim50269362016-12-23 11:22:02 +09001239 + listener + " is set by " + getCallingPackageName(uid));
1240
1241 if (user.mOnVolumeKeyLongPressListener != null) {
1242 try {
1243 user.mOnVolumeKeyLongPressListener.asBinder().linkToDeath(
1244 new IBinder.DeathRecipient() {
1245 @Override
1246 public void binderDied() {
1247 synchronized (mLock) {
1248 user.mOnVolumeKeyLongPressListener = null;
1249 }
1250 }
1251 }, 0);
1252 } catch (RemoteException e) {
1253 Log.w(TAG, "Failed to set death recipient "
1254 + user.mOnVolumeKeyLongPressListener);
1255 user.mOnVolumeKeyLongPressListener = null;
1256 }
1257 }
1258 }
1259 } finally {
1260 Binder.restoreCallingIdentity(token);
1261 }
1262 }
1263
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001264 @Override
1265 public void setOnMediaKeyListener(IOnMediaKeyListener listener) {
1266 final int pid = Binder.getCallingPid();
1267 final int uid = Binder.getCallingUid();
1268 final long token = Binder.clearCallingIdentity();
1269 try {
1270 // Enforce SET_MEDIA_KEY_LISTENER permission.
1271 if (getContext().checkPermission(
1272 android.Manifest.permission.SET_MEDIA_KEY_LISTENER, pid, uid)
1273 != PackageManager.PERMISSION_GRANTED) {
1274 throw new SecurityException("Must hold the SET_MEDIA_KEY_LISTENER" +
1275 " permission.");
1276 }
1277
1278 synchronized (mLock) {
1279 int userId = UserHandle.getUserId(uid);
Jaewan Kima7dce192017-02-16 17:10:54 +09001280 FullUserRecord user = getFullUserRecordLocked(userId);
1281 if (user == null || user.mFullUserId != userId) {
1282 Log.w(TAG, "Only the full user can set the media key listener"
1283 + ", userId=" + userId);
1284 return;
1285 }
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001286 if (user.mOnMediaKeyListener != null && user.mOnMediaKeyListenerUid != uid) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001287 Log.w(TAG, "The media key listener cannot be reset by another app. "
1288 + ", mOnMediaKeyListenerUid=" + user.mOnMediaKeyListenerUid
1289 + ", uid=" + uid);
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001290 return;
1291 }
1292
1293 user.mOnMediaKeyListener = listener;
1294 user.mOnMediaKeyListenerUid = uid;
1295
Jaewan Kima7dce192017-02-16 17:10:54 +09001296 Log.d(TAG, "The media key listener " + user.mOnMediaKeyListener
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001297 + " is set by " + getCallingPackageName(uid));
1298
1299 if (user.mOnMediaKeyListener != null) {
1300 try {
1301 user.mOnMediaKeyListener.asBinder().linkToDeath(
1302 new IBinder.DeathRecipient() {
1303 @Override
1304 public void binderDied() {
1305 synchronized (mLock) {
1306 user.mOnMediaKeyListener = null;
1307 }
1308 }
1309 }, 0);
1310 } catch (RemoteException e) {
1311 Log.w(TAG, "Failed to set death recipient " + user.mOnMediaKeyListener);
1312 user.mOnMediaKeyListener = null;
1313 }
1314 }
1315 }
1316 } finally {
1317 Binder.restoreCallingIdentity(token);
1318 }
1319 }
1320
Jaewan Kim50269362016-12-23 11:22:02 +09001321 /**
1322 * Handles the dispatching of the volume button events to one of the
1323 * registered listeners. If there's a volume key long-press listener and
1324 * there's no active global priority session, long-pressess will be sent to the
1325 * long-press listener instead of adjusting volume.
1326 *
1327 * @param keyEvent a non-null KeyEvent whose key code is one of the
1328 * {@link KeyEvent#KEYCODE_VOLUME_UP},
1329 * {@link KeyEvent#KEYCODE_VOLUME_DOWN},
1330 * or {@link KeyEvent#KEYCODE_VOLUME_MUTE}.
1331 * @param stream stream type to adjust volume.
1332 * @param musicOnly true if both UI nor haptic feedback aren't needed when adjust volume.
1333 */
1334 @Override
1335 public void dispatchVolumeKeyEvent(KeyEvent keyEvent, int stream, boolean musicOnly) {
1336 if (keyEvent == null ||
1337 (keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_UP
1338 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_DOWN
1339 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_MUTE)) {
1340 Log.w(TAG, "Attempted to dispatch null or non-volume key event.");
1341 return;
1342 }
1343
1344 final int pid = Binder.getCallingPid();
1345 final int uid = Binder.getCallingUid();
1346 final long token = Binder.clearCallingIdentity();
1347
Jaewan Kimb2781e72017-03-02 09:57:09 +09001348 if (DEBUG_KEY_EVENT) {
Jaewan Kim50269362016-12-23 11:22:02 +09001349 Log.d(TAG, "dispatchVolumeKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
1350 + keyEvent);
1351 }
1352
1353 try {
1354 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001355 if (isGlobalPriorityActiveLocked()
1356 || mCurrentFullUserRecord.mOnVolumeKeyLongPressListener == null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001357 dispatchVolumeKeyEventLocked(keyEvent, stream, musicOnly);
1358 } else {
1359 // TODO: Consider the case when both volume up and down keys are pressed
1360 // at the same time.
1361 if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
1362 if (keyEvent.getRepeatCount() == 0) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001363 // Keeps the copy of the KeyEvent because it can be reused.
Jaewan Kima7dce192017-02-16 17:10:54 +09001364 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent =
1365 KeyEvent.obtain(keyEvent);
1366 mCurrentFullUserRecord.mInitialDownVolumeStream = stream;
1367 mCurrentFullUserRecord.mInitialDownMusicOnly = musicOnly;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001368 mHandler.sendMessageDelayed(
1369 mHandler.obtainMessage(
Jaewan Kima7dce192017-02-16 17:10:54 +09001370 MessageHandler.MSG_VOLUME_INITIAL_DOWN,
1371 mCurrentFullUserRecord.mFullUserId, 0),
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001372 mLongPressTimeout);
Jaewan Kim50269362016-12-23 11:22:02 +09001373 }
1374 if (keyEvent.getRepeatCount() > 0 || keyEvent.isLongPress()) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001375 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kima7dce192017-02-16 17:10:54 +09001376 if (mCurrentFullUserRecord.mInitialDownVolumeKeyEvent != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001377 dispatchVolumeKeyLongPressLocked(
Jaewan Kima7dce192017-02-16 17:10:54 +09001378 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent);
Jaewan Kim50269362016-12-23 11:22:02 +09001379 // Mark that the key is already handled.
Jaewan Kima7dce192017-02-16 17:10:54 +09001380 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent = null;
Jaewan Kim50269362016-12-23 11:22:02 +09001381 }
1382 dispatchVolumeKeyLongPressLocked(keyEvent);
1383 }
1384 } else { // if up
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001385 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kima7dce192017-02-16 17:10:54 +09001386 if (mCurrentFullUserRecord.mInitialDownVolumeKeyEvent != null
1387 && mCurrentFullUserRecord.mInitialDownVolumeKeyEvent
1388 .getDownTime() == keyEvent.getDownTime()) {
Jaewan Kim50269362016-12-23 11:22:02 +09001389 // Short-press. Should change volume.
1390 dispatchVolumeKeyEventLocked(
Jaewan Kima7dce192017-02-16 17:10:54 +09001391 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent,
1392 mCurrentFullUserRecord.mInitialDownVolumeStream,
1393 mCurrentFullUserRecord.mInitialDownMusicOnly);
Jaewan Kim50269362016-12-23 11:22:02 +09001394 dispatchVolumeKeyEventLocked(keyEvent, stream, musicOnly);
1395 } else {
1396 dispatchVolumeKeyLongPressLocked(keyEvent);
1397 }
1398 }
1399 }
1400 }
1401 } finally {
1402 Binder.restoreCallingIdentity(token);
1403 }
1404 }
1405
Jaewan Kim50269362016-12-23 11:22:02 +09001406 private void dispatchVolumeKeyEventLocked(
1407 KeyEvent keyEvent, int stream, boolean musicOnly) {
1408 boolean down = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
1409 boolean up = keyEvent.getAction() == KeyEvent.ACTION_UP;
1410 int direction = 0;
1411 boolean isMute = false;
1412 switch (keyEvent.getKeyCode()) {
1413 case KeyEvent.KEYCODE_VOLUME_UP:
1414 direction = AudioManager.ADJUST_RAISE;
1415 break;
1416 case KeyEvent.KEYCODE_VOLUME_DOWN:
1417 direction = AudioManager.ADJUST_LOWER;
1418 break;
1419 case KeyEvent.KEYCODE_VOLUME_MUTE:
1420 isMute = true;
1421 break;
1422 }
1423 if (down || up) {
1424 int flags = AudioManager.FLAG_FROM_KEY;
1425 if (musicOnly) {
1426 // This flag is used when the screen is off to only affect active media.
1427 flags |= AudioManager.FLAG_ACTIVE_MEDIA_ONLY;
1428 } else {
1429 // These flags are consistent with the home screen
1430 if (up) {
1431 flags |= AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_VIBRATE;
1432 } else {
1433 flags |= AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_VIBRATE;
1434 }
1435 }
1436 if (direction != 0) {
1437 // If this is action up we want to send a beep for non-music events
1438 if (up) {
1439 direction = 0;
1440 }
1441 dispatchAdjustVolumeLocked(stream, direction, flags);
1442 } else if (isMute) {
1443 if (down && keyEvent.getRepeatCount() == 0) {
1444 dispatchAdjustVolumeLocked(stream, AudioManager.ADJUST_TOGGLE_MUTE, flags);
1445 }
1446 }
1447 }
1448 }
1449
1450 @Override
RoboErik7c82ced2014-12-04 17:39:08 -08001451 public void dispatchAdjustVolume(int suggestedStream, int delta, int flags) {
RoboErikb69ffd42014-05-30 14:57:59 -07001452 final long token = Binder.clearCallingIdentity();
1453 try {
1454 synchronized (mLock) {
Jaewan Kim50269362016-12-23 11:22:02 +09001455 dispatchAdjustVolumeLocked(suggestedStream, delta, flags);
RoboErikb69ffd42014-05-30 14:57:59 -07001456 }
1457 } finally {
1458 Binder.restoreCallingIdentity(token);
1459 }
1460 }
1461
1462 @Override
RoboErik19c95182014-06-23 15:38:48 -07001463 public void setRemoteVolumeController(IRemoteVolumeController rvc) {
1464 final int pid = Binder.getCallingPid();
1465 final int uid = Binder.getCallingUid();
1466 final long token = Binder.clearCallingIdentity();
1467 try {
John Spurlockeb69e242015-02-17 17:15:04 -05001468 enforceSystemUiPermission("listen for volume changes", pid, uid);
RoboErik19c95182014-06-23 15:38:48 -07001469 mRvc = rvc;
1470 } finally {
1471 Binder.restoreCallingIdentity(token);
1472 }
1473 }
1474
1475 @Override
RoboErikde9ba392014-09-26 12:51:01 -07001476 public boolean isGlobalPriorityActive() {
Jaewan Kim51255012017-02-24 16:19:14 +09001477 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001478 return isGlobalPriorityActiveLocked();
Jaewan Kim51255012017-02-24 16:19:14 +09001479 }
RoboErikde9ba392014-09-26 12:51:01 -07001480 }
1481
1482 @Override
RoboErika278ea72014-04-24 14:49:01 -07001483 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001484 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
RoboErika278ea72014-04-24 14:49:01 -07001485
1486 pw.println("MEDIA SESSION SERVICE (dumpsys media_session)");
1487 pw.println();
1488
1489 synchronized (mLock) {
RoboErika08adb242014-11-21 18:28:18 -08001490 pw.println(mSessionsListeners.size() + " sessions listeners.");
Jaewan Kima7dce192017-02-16 17:10:54 +09001491 pw.println("Global priority session is " + mGlobalPrioritySession);
Jaewan Kim101b4d52017-05-18 13:23:11 +09001492 if (mGlobalPrioritySession != null) {
1493 mGlobalPrioritySession.dump(pw, " ");
1494 }
RoboErik4646d282014-05-13 10:13:04 -07001495 pw.println("User Records:");
Jaewan Kime0ca3f32017-02-16 15:52:39 +09001496 int count = mUserRecords.size();
RoboErika278ea72014-04-24 14:49:01 -07001497 for (int i = 0; i < count; i++) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001498 mUserRecords.valueAt(i).dumpLocked(pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001499 }
Sungsoo Lim875e6972017-11-03 02:22:35 +00001500 mAudioPlayerStateMonitor.dump(getContext(), pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001501 }
1502 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001503
Jaewan Kim7e9e4d92018-02-13 22:20:41 +09001504 /**
Jaewan Kimfed49502018-03-05 17:51:12 +09001505 * Returns if the controller's package is trusted (i.e. has either MEDIA_CONTENT_CONTROL
1506 * permission or an enabled notification listener)
1507 *
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001508 * @param controllerPackageName package name of the controller app
1509 * @param controllerPid pid of the controller app
1510 * @param controllerUid uid of the controller app
Jaewan Kimfed49502018-03-05 17:51:12 +09001511 */
1512 @Override
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001513 public boolean isTrusted(String controllerPackageName, int controllerPid, int controllerUid)
1514 throws RemoteException {
1515 final int uid = Binder.getCallingUid();
Jaewan Kimfed49502018-03-05 17:51:12 +09001516 final long token = Binder.clearCallingIdentity();
1517 try {
Jaewan Kim03cba652018-04-04 16:25:35 +09001518 int controllerUserId = UserHandle.getUserId(controllerUid);
1519 int controllerUidFromPackageName;
1520 try {
1521 controllerUidFromPackageName = getContext().getPackageManager()
1522 .getPackageUidAsUser(controllerPackageName, controllerUserId);
1523 } catch (NameNotFoundException e) {
1524 if (DEBUG) {
1525 Log.d(TAG, "Package " + controllerPackageName + " doesn't exist");
1526 }
1527 return false;
1528 }
1529 if (controllerUidFromPackageName != controllerUid) {
1530 if (DEBUG) {
1531 Log.d(TAG, "Package name " + controllerPackageName
1532 + " doesn't match with the uid " + controllerUid);
1533 }
1534 return false;
1535 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001536 return hasMediaControlPermission(UserHandle.getUserId(uid), controllerPackageName,
1537 controllerPid, controllerUid);
Jaewan Kimfed49502018-03-05 17:51:12 +09001538 } finally {
1539 Binder.restoreCallingIdentity(token);
1540 }
Jaewan Kimfed49502018-03-05 17:51:12 +09001541 }
1542
1543 /**
Jaewan Kim7e9e4d92018-02-13 22:20:41 +09001544 * Called when a {@link android.media.MediaSession2} instance is created.
1545 * <p>
1546 * This does two things.
1547 * 1. Keep the newly created session in the service
1548 * 2. Do sanity check to ensure unique id per package, and return result
1549 *
1550 * @param sessionToken SessionToken2 object in bundled form
1551 * @return {@code true} if the session's id isn't used by the package now. {@code false}
1552 * otherwise.
1553 */
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001554 @Override
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001555 public boolean createSession2(Bundle sessionToken) {
Jaewan Kim129a5622018-03-28 12:19:04 +09001556 if (!USE_MEDIA2_APIS) {
1557 return false;
1558 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001559 final int uid = Binder.getCallingUid();
Christofer Ã…kersten6823d812018-03-22 23:20:39 +09001560 final SessionToken2 token = SessionToken2.fromBundle(sessionToken);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001561 if (token == null || token.getUid() != uid) {
1562 Log.w(TAG, "onSessionCreated failed, expected caller uid=" + token.getUid()
1563 + " but from uid=" + uid);
1564 }
1565 if (DEBUG) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001566 Log.d(TAG, "createSession2: " + token);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001567 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001568 synchronized (mLock) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001569 MediaController2 controller = mSessionRecords.get(token);
1570 if (controller != null && controller.isConnected()) {
1571 return false;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001572 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001573 Context context = getContext();
Sungsoo Lim375efa12018-03-02 10:17:08 +09001574 controller = new MediaController2(context, token, context.getMainExecutor(),
1575 new ControllerCallback(token));
1576 if (addSessionRecordLocked(token, controller)) {
1577 postSessionTokensUpdated(UserHandle.getUserId(token.getUid()));
1578 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001579 return true;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001580 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001581 }
1582
Jaewan Kim7e9e4d92018-02-13 22:20:41 +09001583 /**
1584 * Called when a {@link android.media.MediaSession2} instance is closed. (i.e. destroyed)
1585 * <p>
1586 * Ideally service should know that a session is destroyed through the
1587 * {@link android.media.MediaController2.ControllerCallback#onDisconnected()}, which is
1588 * asynchronous call. However, we also need synchronous way together to address timing
1589 * issue. If the package recreates the session almost immediately, which happens commonly
1590 * for tests, service will reject the creation through {@link #onSessionCreated(Bundle)}
1591 * if the service hasn't notified previous destroy yet. This synchronous API will address
1592 * the issue.
1593 *
1594 * @param sessionToken SessionToken2 object in bundled form
1595 */
Jaewan Kimf7a77062018-01-27 01:34:24 +09001596 @Override
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001597 public void destroySession2(Bundle sessionToken) {
Jaewan Kim129a5622018-03-28 12:19:04 +09001598 if (!USE_MEDIA2_APIS) {
1599 return;
1600 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001601 final int uid = Binder.getCallingUid();
Christofer Ã…kersten6823d812018-03-22 23:20:39 +09001602 final SessionToken2 token = SessionToken2.fromBundle(sessionToken);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001603 if (token == null || token.getUid() != uid) {
1604 Log.w(TAG, "onSessionDestroyed failed, expected caller uid=" + token.getUid()
1605 + " but from uid=" + uid);
1606 }
1607 if (DEBUG) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001608 Log.d(TAG, "destroySession2 " + token);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001609 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001610 destroySession2Internal(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001611 }
1612
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001613 // TODO(jaewan): Make this API take userId as an argument (b/73597722)
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001614 @Override
1615 public List<Bundle> getSessionTokens(boolean activeSessionOnly,
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001616 boolean sessionServiceOnly, String packageName) throws RemoteException {
Jaewan Kim129a5622018-03-28 12:19:04 +09001617 if (!USE_MEDIA2_APIS) {
1618 return null;
1619 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001620 final int pid = Binder.getCallingPid();
1621 final int uid = Binder.getCallingUid();
1622 final long token = Binder.clearCallingIdentity();
1623
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001624 List<Bundle> tokens = new ArrayList<>();
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001625 try {
1626 verifySessionsRequest2(UserHandle.getUserId(uid), packageName, pid, uid);
1627 synchronized (mLock) {
1628 for (Map.Entry<SessionToken2, MediaController2> record
1629 : mSessionRecords.entrySet()) {
1630 boolean isSessionService = (record.getKey().getType() != TYPE_SESSION);
1631 boolean isActive = record.getValue() != null;
1632 if ((activeSessionOnly && !isActive)
1633 || (sessionServiceOnly && !isSessionService)) {
1634 continue;
1635 }
1636 tokens.add(record.getKey().toBundle());
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001637 }
1638 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001639 } finally {
1640 Binder.restoreCallingIdentity(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001641 }
1642 return tokens;
1643 }
1644
Jaewan Kim379e30d2018-01-29 11:57:04 +09001645 @Override
1646 public void addSessionTokensListener(ISessionTokensListener listener, int userId,
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001647 String packageName) throws RemoteException {
Jaewan Kim129a5622018-03-28 12:19:04 +09001648 if (!USE_MEDIA2_APIS) {
1649 return;
1650 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001651 final int pid = Binder.getCallingPid();
1652 final int uid = Binder.getCallingUid();
1653 final long token = Binder.clearCallingIdentity();
1654 try {
1655 int resolvedUserId = verifySessionsRequest2(userId, packageName, pid, uid);
1656 synchronized (mLock) {
1657 final SessionTokensListenerRecord record =
1658 new SessionTokensListenerRecord(listener, resolvedUserId);
1659 try {
1660 listener.asBinder().linkToDeath(record, 0);
1661 } catch (RemoteException e) {
1662 }
1663 mSessionTokensListeners.add(record);
Sungsoo Lim375efa12018-03-02 10:17:08 +09001664 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001665 } finally {
1666 Binder.restoreCallingIdentity(token);
Sungsoo Lim375efa12018-03-02 10:17:08 +09001667 }
Jaewan Kim379e30d2018-01-29 11:57:04 +09001668 }
1669
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001670 // TODO(jaewan): Make this API take userId as an argument (b/73597722)
Jaewan Kim379e30d2018-01-29 11:57:04 +09001671 @Override
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001672 public void removeSessionTokensListener(ISessionTokensListener listener,
1673 String packageName) throws RemoteException {
Jaewan Kim129a5622018-03-28 12:19:04 +09001674 if (!USE_MEDIA2_APIS) {
1675 return;
1676 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001677 final int pid = Binder.getCallingPid();
1678 final int uid = Binder.getCallingUid();
1679 final long token = Binder.clearCallingIdentity();
1680 try {
1681 verifySessionsRequest2(UserHandle.getUserId(uid), packageName, pid, uid);
1682 synchronized (mLock) {
1683 IBinder listenerBinder = listener.asBinder();
1684 for (SessionTokensListenerRecord record : mSessionTokensListeners) {
1685 if (listenerBinder.equals(record.mListener.asBinder())) {
1686 try {
1687 listenerBinder.unlinkToDeath(record, 0);
1688 } catch (NoSuchElementException e) {
1689 }
1690 mSessionTokensListeners.remove(record);
1691 break;
Sungsoo Lim375efa12018-03-02 10:17:08 +09001692 }
Sungsoo Lim375efa12018-03-02 10:17:08 +09001693 }
1694 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001695 } finally {
1696 Binder.restoreCallingIdentity(token);
Sungsoo Lim375efa12018-03-02 10:17:08 +09001697 }
Jaewan Kim379e30d2018-01-29 11:57:04 +09001698 }
1699
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001700 // For MediaSession
RoboErik2e7a9162014-06-04 16:53:45 -07001701 private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
1702 final int uid) {
1703 String packageName = null;
1704 if (componentName != null) {
1705 // If they gave us a component name verify they own the
1706 // package
1707 packageName = componentName.getPackageName();
1708 enforcePackageName(packageName, uid);
1709 }
1710 // Check that they can make calls on behalf of the user and
1711 // get the final user id
1712 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
1713 true /* allowAll */, true /* requireFull */, "getSessions", packageName);
1714 // Check if they have the permissions or their component is
1715 // enabled for the user they're calling from.
1716 enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
1717 return resolvedUserId;
1718 }
1719
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001720 // For MediaSession2
1721 private int verifySessionsRequest2(int targetUserId, String callerPackageName,
1722 int callerPid, int callerUid) throws RemoteException {
1723 // Check that they can make calls on behalf of the user and get the final user id.
1724 int resolvedUserId = ActivityManager.handleIncomingUser(callerPid, callerUid,
1725 targetUserId, true /* allowAll */, true /* requireFull */, "getSessionTokens",
1726 callerPackageName);
1727 // Check if they have the permissions or their component is
1728 // enabled for the user they're calling from.
1729 if (!hasMediaControlPermission(
1730 resolvedUserId, callerPackageName, callerPid, callerUid)) {
1731 throw new SecurityException("Missing permission to control media.");
1732 }
1733 return resolvedUserId;
1734 }
1735
1736 // For MediaSession2
1737 private boolean hasMediaControlPermission(int resolvedUserId, String packageName,
1738 int pid, int uid) throws RemoteException {
1739 // Allow API calls from the System UI
1740 if (isCurrentVolumeController(pid, uid)) {
1741 return true;
1742 }
1743
1744 // Check if it's system server or has MEDIA_CONTENT_CONTROL.
1745 // Note that system server doesn't have MEDIA_CONTENT_CONTROL, so we need extra
1746 // check here.
1747 if (uid == Process.SYSTEM_UID || getContext().checkPermission(
1748 android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
1749 == PackageManager.PERMISSION_GRANTED) {
1750 return true;
1751 } else if (DEBUG) {
1752 Log.d(TAG, packageName + " (uid=" + uid + ") hasn't granted MEDIA_CONTENT_CONTROL");
1753 }
1754
1755 // You may not access another user's content as an enabled listener.
1756 final int userId = UserHandle.getUserId(uid);
1757 if (resolvedUserId != userId) {
1758 return false;
1759 }
1760
1761 // TODO(jaewan): (Post-P) Propose NotificationManager#hasEnabledNotificationListener(
1762 // String pkgName) to notification team for optimization
1763 final List<ComponentName> enabledNotificationListeners =
1764 mNotificationManager.getEnabledNotificationListeners(userId);
1765 if (enabledNotificationListeners != null) {
1766 for (int i = 0; i < enabledNotificationListeners.size(); i++) {
1767 if (TextUtils.equals(packageName,
1768 enabledNotificationListeners.get(i).getPackageName())) {
1769 return true;
1770 }
1771 }
1772 }
1773 if (DEBUG) {
1774 Log.d(TAG, packageName + " (uid=" + uid + ") doesn't have an enabled "
1775 + "notification listener");
1776 }
1777 return false;
1778 }
1779
Jaewan Kim50269362016-12-23 11:22:02 +09001780 private void dispatchAdjustVolumeLocked(int suggestedStream, int direction, int flags) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001781 MediaSessionRecord session = isGlobalPriorityActiveLocked() ? mGlobalPrioritySession
1782 : mCurrentFullUserRecord.mPriorityStack.getDefaultVolumeSession();
Jaewan Kim50269362016-12-23 11:22:02 +09001783
RoboErik9c785402014-11-11 16:52:26 -08001784 boolean preferSuggestedStream = false;
1785 if (isValidLocalStreamType(suggestedStream)
1786 && AudioSystem.isStreamActive(suggestedStream, 0)) {
1787 preferSuggestedStream = true;
1788 }
Jaewan Kimb2781e72017-03-02 09:57:09 +09001789 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001790 Log.d(TAG, "Adjusting " + session + " by " + direction + ". flags="
1791 + flags + ", suggestedStream=" + suggestedStream
1792 + ", preferSuggestedStream=" + preferSuggestedStream);
1793 }
RoboErik9c785402014-11-11 16:52:26 -08001794 if (session == null || preferSuggestedStream) {
RoboErik94c716e2014-09-14 13:54:31 -07001795 if ((flags & AudioManager.FLAG_ACTIVE_MEDIA_ONLY) != 0
1796 && !AudioSystem.isStreamActive(AudioManager.STREAM_MUSIC, 0)) {
RoboErik3c45c292014-07-08 16:47:31 -07001797 if (DEBUG) {
1798 Log.d(TAG, "No active session to adjust, skipping media only volume event");
RoboErik3c45c292014-07-08 16:47:31 -07001799 }
RoboErikb7c014c2014-07-22 15:58:22 -07001800 return;
RoboErik3c45c292014-07-08 16:47:31 -07001801 }
Shibin George19e84042016-06-14 20:42:13 +05301802
1803 // Execute mAudioService.adjustSuggestedStreamVolume() on
1804 // handler thread of MediaSessionService.
1805 // This will release the MediaSessionService.mLock sooner and avoid
1806 // a potential deadlock between MediaSessionService.mLock and
1807 // ActivityManagerService lock.
1808 mHandler.post(new Runnable() {
1809 @Override
1810 public void run() {
1811 try {
1812 String packageName = getContext().getOpPackageName();
1813 mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
1814 flags, packageName, TAG);
1815 } catch (RemoteException e) {
1816 Log.e(TAG, "Error adjusting default volume.", e);
Hyundo Moon739d6c22017-09-18 17:01:48 +09001817 } catch (IllegalArgumentException e) {
1818 Log.e(TAG, "Cannot adjust volume: direction=" + direction
1819 + ", suggestedStream=" + suggestedStream + ", flags=" + flags,
1820 e);
Shibin George19e84042016-06-14 20:42:13 +05301821 }
1822 }
1823 });
RoboErikb69ffd42014-05-30 14:57:59 -07001824 } else {
Hyundo Moonb1e344e2018-03-22 17:22:14 +09001825 session.adjustVolume(getContext().getPackageName(), Process.myPid(),
1826 Process.SYSTEM_UID, direction, flags, true);
RoboErikb69ffd42014-05-30 14:57:59 -07001827 }
1828 }
1829
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001830 private void handleVoiceKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock) {
RoboErik9a9d0b52014-05-20 14:53:39 -07001831 int action = keyEvent.getAction();
1832 boolean isLongPress = (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0;
1833 if (action == KeyEvent.ACTION_DOWN) {
1834 if (keyEvent.getRepeatCount() == 0) {
1835 mVoiceButtonDown = true;
1836 mVoiceButtonHandled = false;
1837 } else if (mVoiceButtonDown && !mVoiceButtonHandled && isLongPress) {
1838 mVoiceButtonHandled = true;
1839 startVoiceInput(needWakeLock);
1840 }
1841 } else if (action == KeyEvent.ACTION_UP) {
1842 if (mVoiceButtonDown) {
1843 mVoiceButtonDown = false;
1844 if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
1845 // Resend the down then send this event through
1846 KeyEvent downEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_DOWN);
Jaewan Kim98003d32017-02-24 18:33:04 +09001847 dispatchMediaKeyEventLocked(downEvent, needWakeLock);
1848 dispatchMediaKeyEventLocked(keyEvent, needWakeLock);
RoboErik9a9d0b52014-05-20 14:53:39 -07001849 }
1850 }
1851 }
1852 }
1853
Jaewan Kim98003d32017-02-24 18:33:04 +09001854 private void dispatchMediaKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001855 MediaSessionRecord session = mCurrentFullUserRecord.getMediaButtonSessionLocked();
RoboErik9a9d0b52014-05-20 14:53:39 -07001856 if (session != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001857 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001858 Log.d(TAG, "Sending " + keyEvent + " to " + session);
RoboErik9a9d0b52014-05-20 14:53:39 -07001859 }
1860 if (needWakeLock) {
1861 mKeyEventReceiver.aquireWakeLockLocked();
1862 }
Jaewan Kim50269362016-12-23 11:22:02 +09001863 // If we don't need a wakelock use -1 as the id so we won't release it later.
Hyundo Moonb1e344e2018-03-22 17:22:14 +09001864 session.sendMediaButton(getContext().getPackageName(),
1865 Process.myPid(),
1866 Process.SYSTEM_UID,
1867 keyEvent,
RoboErik9a9d0b52014-05-20 14:53:39 -07001868 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
Hyundo Moonb1e344e2018-03-22 17:22:14 +09001869 mKeyEventReceiver);
Jaewan Kima7dce192017-02-16 17:10:54 +09001870 if (mCurrentFullUserRecord.mCallback != null) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001871 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001872 mCurrentFullUserRecord.mCallback.onMediaKeyEventDispatchedToMediaSession(
1873 keyEvent,
Jaewan Kimbd16f452017-02-03 16:21:38 +09001874 new MediaSession.Token(session.getControllerBinder()));
1875 } catch (RemoteException e) {
1876 Log.w(TAG, "Failed to send callback", e);
1877 }
1878 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001879 } else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null
1880 || mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
1881 if (needWakeLock) {
1882 mKeyEventReceiver.aquireWakeLockLocked();
1883 }
1884 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
1885 mediaButtonIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1886 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
1887 try {
1888 if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
1889 PendingIntent receiver = mCurrentFullUserRecord.mLastMediaButtonReceiver;
1890 if (DEBUG_KEY_EVENT) {
1891 Log.d(TAG, "Sending " + keyEvent
Jaewan Kim92dea332017-02-02 11:52:08 +09001892 + " to the last known PendingIntent " + receiver);
Jaewan Kima7dce192017-02-16 17:10:54 +09001893 }
1894 receiver.send(getContext(),
1895 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
1896 mediaButtonIntent, mKeyEventReceiver, mHandler);
1897 if (mCurrentFullUserRecord.mCallback != null) {
1898 ComponentName componentName = mCurrentFullUserRecord
1899 .mLastMediaButtonReceiver.getIntent().getComponent();
1900 if (componentName != null) {
1901 mCurrentFullUserRecord.mCallback
1902 .onMediaKeyEventDispatchedToMediaButtonReceiver(
1903 keyEvent, componentName);
Jaewan Kimbd16f452017-02-03 16:21:38 +09001904 }
RoboErikc8f92d12015-01-05 16:48:07 -08001905 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001906 } else {
1907 ComponentName receiver =
1908 mCurrentFullUserRecord.mRestoredMediaButtonReceiver;
1909 if (DEBUG_KEY_EVENT) {
1910 Log.d(TAG, "Sending " + keyEvent + " to the restored intent "
1911 + receiver);
1912 }
1913 mediaButtonIntent.setComponent(receiver);
1914 getContext().sendBroadcastAsUser(mediaButtonIntent,
Jaewan Kim92dea332017-02-02 11:52:08 +09001915 UserHandle.of(mCurrentFullUserRecord
1916 .mRestoredMediaButtonReceiverUserId));
Jaewan Kima7dce192017-02-16 17:10:54 +09001917 if (mCurrentFullUserRecord.mCallback != null) {
1918 mCurrentFullUserRecord.mCallback
1919 .onMediaKeyEventDispatchedToMediaButtonReceiver(
1920 keyEvent, receiver);
1921 }
RoboErikb214efb2014-07-24 13:20:30 -07001922 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001923 } catch (CanceledException e) {
1924 Log.i(TAG, "Error sending key event to media button receiver "
1925 + mCurrentFullUserRecord.mLastMediaButtonReceiver, e);
1926 } catch (RemoteException e) {
1927 Log.w(TAG, "Failed to send callback", e);
RoboErik9a9d0b52014-05-20 14:53:39 -07001928 }
RoboErik9a9d0b52014-05-20 14:53:39 -07001929 }
1930 }
1931
1932 private void startVoiceInput(boolean needWakeLock) {
1933 Intent voiceIntent = null;
1934 // select which type of search to launch:
1935 // - screen on and device unlocked: action is ACTION_WEB_SEARCH
1936 // - device locked or screen off: action is
1937 // ACTION_VOICE_SEARCH_HANDS_FREE
1938 // with EXTRA_SECURE set to true if the device is securely locked
1939 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1940 boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
1941 if (!isLocked && pm.isScreenOn()) {
1942 voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
1943 Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
1944 } else {
1945 voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
1946 voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
1947 isLocked && mKeyguardManager.isKeyguardSecure());
1948 Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
1949 }
1950 // start the search activity
1951 if (needWakeLock) {
1952 mMediaEventWakeLock.acquire();
1953 }
1954 try {
1955 if (voiceIntent != null) {
1956 voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1957 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Jaewan Kim8f729082016-06-21 12:36:26 +09001958 if (DEBUG) Log.d(TAG, "voiceIntent: " + voiceIntent);
RoboErik9a9d0b52014-05-20 14:53:39 -07001959 getContext().startActivityAsUser(voiceIntent, UserHandle.CURRENT);
1960 }
1961 } catch (ActivityNotFoundException e) {
1962 Log.w(TAG, "No activity for search: " + e);
1963 } finally {
1964 if (needWakeLock) {
1965 mMediaEventWakeLock.release();
1966 }
1967 }
1968 }
1969
1970 private boolean isVoiceKey(int keyCode) {
Jaewan Kimba18d8e2017-05-12 17:37:57 +09001971 return keyCode == KeyEvent.KEYCODE_HEADSETHOOK
Jaewan Kimfdb612e2017-07-01 09:23:41 +09001972 || (!mHasFeatureLeanback && keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
RoboErik9a9d0b52014-05-20 14:53:39 -07001973 }
1974
Jeff Brown38d3feb2015-03-19 18:26:30 -07001975 private boolean isUserSetupComplete() {
1976 return Settings.Secure.getIntForUser(getContext().getContentResolver(),
1977 Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1978 }
1979
RoboErik9c785402014-11-11 16:52:26 -08001980 // we only handle public stream types, which are 0-5
1981 private boolean isValidLocalStreamType(int streamType) {
1982 return streamType >= AudioManager.STREAM_VOICE_CALL
1983 && streamType <= AudioManager.STREAM_NOTIFICATION;
1984 }
1985
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001986 private class MediaKeyListenerResultReceiver extends ResultReceiver implements Runnable {
1987 private KeyEvent mKeyEvent;
1988 private boolean mNeedWakeLock;
1989 private boolean mHandled;
1990
1991 private MediaKeyListenerResultReceiver(KeyEvent keyEvent, boolean needWakeLock) {
1992 super(mHandler);
1993 mHandler.postDelayed(this, MEDIA_KEY_LISTENER_TIMEOUT);
1994 mKeyEvent = keyEvent;
1995 mNeedWakeLock = needWakeLock;
1996 }
1997
1998 @Override
1999 public void run() {
2000 Log.d(TAG, "The media key listener is timed-out for " + mKeyEvent);
2001 dispatchMediaKeyEvent();
2002 }
2003
2004 @Override
2005 protected void onReceiveResult(int resultCode, Bundle resultData) {
2006 if (resultCode == MediaSessionManager.RESULT_MEDIA_KEY_HANDLED) {
2007 mHandled = true;
2008 mHandler.removeCallbacks(this);
2009 return;
2010 }
2011 dispatchMediaKeyEvent();
2012 }
2013
2014 private void dispatchMediaKeyEvent() {
2015 if (mHandled) {
2016 return;
2017 }
2018 mHandled = true;
2019 mHandler.removeCallbacks(this);
2020 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09002021 if (!isGlobalPriorityActiveLocked()
Jaewan Kim98003d32017-02-24 18:33:04 +09002022 && isVoiceKey(mKeyEvent.getKeyCode())) {
2023 handleVoiceKeyEventLocked(mKeyEvent, mNeedWakeLock);
2024 } else {
2025 dispatchMediaKeyEventLocked(mKeyEvent, mNeedWakeLock);
2026 }
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08002027 }
2028 }
2029 }
2030
RoboErik418c10c2014-05-19 09:25:25 -07002031 private KeyEventWakeLockReceiver mKeyEventReceiver = new KeyEventWakeLockReceiver(mHandler);
2032
RoboErikb214efb2014-07-24 13:20:30 -07002033 class KeyEventWakeLockReceiver extends ResultReceiver implements Runnable,
2034 PendingIntent.OnFinished {
RoboErik418c10c2014-05-19 09:25:25 -07002035 private final Handler mHandler;
2036 private int mRefCount = 0;
2037 private int mLastTimeoutId = 0;
2038
2039 public KeyEventWakeLockReceiver(Handler handler) {
2040 super(handler);
2041 mHandler = handler;
2042 }
2043
2044 public void onTimeout() {
2045 synchronized (mLock) {
2046 if (mRefCount == 0) {
2047 // We've already released it, so just return
2048 return;
2049 }
2050 mLastTimeoutId++;
2051 mRefCount = 0;
2052 releaseWakeLockLocked();
2053 }
2054 }
2055
2056 public void aquireWakeLockLocked() {
2057 if (mRefCount == 0) {
2058 mMediaEventWakeLock.acquire();
2059 }
2060 mRefCount++;
2061 mHandler.removeCallbacks(this);
2062 mHandler.postDelayed(this, WAKELOCK_TIMEOUT);
2063
2064 }
2065
2066 @Override
2067 public void run() {
2068 onTimeout();
2069 }
2070
RoboErik8a2cfc32014-05-16 11:19:38 -07002071 @Override
2072 protected void onReceiveResult(int resultCode, Bundle resultData) {
RoboErik418c10c2014-05-19 09:25:25 -07002073 if (resultCode < mLastTimeoutId) {
2074 // Ignore results from calls that were before the last
2075 // timeout, just in case.
2076 return;
2077 } else {
2078 synchronized (mLock) {
2079 if (mRefCount > 0) {
2080 mRefCount--;
2081 if (mRefCount == 0) {
2082 releaseWakeLockLocked();
2083 }
2084 }
RoboErik8a2cfc32014-05-16 11:19:38 -07002085 }
2086 }
2087 }
RoboErik418c10c2014-05-19 09:25:25 -07002088
2089 private void releaseWakeLockLocked() {
2090 mMediaEventWakeLock.release();
2091 mHandler.removeCallbacks(this);
2092 }
RoboErikb214efb2014-07-24 13:20:30 -07002093
2094 @Override
2095 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
2096 String resultData, Bundle resultExtras) {
2097 onReceiveResult(resultCode, null);
2098 }
RoboErik8a2cfc32014-05-16 11:19:38 -07002099 };
2100
2101 BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
2102 @Override
2103 public void onReceive(Context context, Intent intent) {
2104 if (intent == null) {
2105 return;
2106 }
2107 Bundle extras = intent.getExtras();
2108 if (extras == null) {
2109 return;
2110 }
2111 synchronized (mLock) {
2112 if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)
2113 && mMediaEventWakeLock.isHeld()) {
2114 mMediaEventWakeLock.release();
2115 }
2116 }
2117 }
2118 };
RoboErik01fe6612014-02-13 14:19:04 -08002119 }
2120
RoboErik2e7a9162014-06-04 16:53:45 -07002121 final class MessageHandler extends Handler {
2122 private static final int MSG_SESSIONS_CHANGED = 1;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09002123 private static final int MSG_VOLUME_INITIAL_DOWN = 2;
Sungsoo Lim375efa12018-03-02 10:17:08 +09002124 private static final int MSG_SESSIONS_TOKENS_CHANGED = 3;
Jaewan Kim92dea332017-02-02 11:52:08 +09002125 private final SparseArray<Integer> mIntegerCache = new SparseArray<>();
RoboErik2e7a9162014-06-04 16:53:45 -07002126
2127 @Override
2128 public void handleMessage(Message msg) {
2129 switch (msg.what) {
2130 case MSG_SESSIONS_CHANGED:
Jaewan Kim92dea332017-02-02 11:52:08 +09002131 pushSessionsChanged((int) msg.obj);
RoboErik2e7a9162014-06-04 16:53:45 -07002132 break;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09002133 case MSG_VOLUME_INITIAL_DOWN:
2134 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09002135 FullUserRecord user = mUserRecords.get((int) msg.arg1);
Jaewan Kimd61a87b2017-02-17 23:14:10 +09002136 if (user != null && user.mInitialDownVolumeKeyEvent != null) {
2137 dispatchVolumeKeyLongPressLocked(user.mInitialDownVolumeKeyEvent);
2138 // Mark that the key is already handled.
2139 user.mInitialDownVolumeKeyEvent = null;
2140 }
2141 }
2142 break;
Sungsoo Lim375efa12018-03-02 10:17:08 +09002143 case MSG_SESSIONS_TOKENS_CHANGED:
2144 pushSessionTokensChanged((int) msg.obj);
2145 break;
RoboErik2e7a9162014-06-04 16:53:45 -07002146 }
2147 }
2148
Jaewan Kim92dea332017-02-02 11:52:08 +09002149 public void postSessionsChanged(int userId) {
2150 // Use object instead of the arguments when posting message to remove pending requests.
2151 Integer userIdInteger = mIntegerCache.get(userId);
2152 if (userIdInteger == null) {
2153 userIdInteger = Integer.valueOf(userId);
2154 mIntegerCache.put(userId, userIdInteger);
2155 }
2156 removeMessages(MSG_SESSIONS_CHANGED, userIdInteger);
2157 obtainMessage(MSG_SESSIONS_CHANGED, userIdInteger).sendToTarget();
RoboErik2e7a9162014-06-04 16:53:45 -07002158 }
2159 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09002160
2161 private class ControllerCallback extends MediaController2.ControllerCallback {
2162
2163 private final SessionToken2 mToken;
2164
2165 ControllerCallback(SessionToken2 token) {
2166 mToken = token;
2167 }
2168
2169 @Override
Jaewan Kim3fb60d52018-03-02 19:23:18 +09002170 public void onDisconnected(MediaController2 controller) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09002171 destroySession2Internal(mToken);
2172 }
2173 };
Sungsoo Lim375efa12018-03-02 10:17:08 +09002174
2175 private final class SessionTokensListenerRecord implements IBinder.DeathRecipient {
2176 private final ISessionTokensListener mListener;
2177 private final int mUserId;
2178
2179 public SessionTokensListenerRecord(ISessionTokensListener listener, int userId) {
2180 mListener = listener;
Jaewan Kim525c88c2018-03-08 10:47:00 +09002181 // TODO(jaewan): should userId be mapped through mFullUserIds? (b/73597722)
Jaewan Kim005e2bb2018-03-02 15:55:12 +09002182 mUserId = userId;
Sungsoo Lim375efa12018-03-02 10:17:08 +09002183 }
2184
2185 @Override
2186 public void binderDied() {
2187 synchronized (mLock) {
2188 mSessionTokensListeners.remove(this);
2189 }
2190 }
2191 }
2192
2193 private void postSessionTokensUpdated(int userId) {
2194 mHandler.obtainMessage(MessageHandler.MSG_SESSIONS_TOKENS_CHANGED, userId).sendToTarget();
2195 }
2196
2197 private void pushSessionTokensChanged(int userId) {
2198 synchronized (mLock) {
2199 List<Bundle> tokens = new ArrayList<>();
2200 for (SessionToken2 token : mSessionRecords.keySet()) {
2201 // TODO(jaewan): Remove the check for UserHandle.USER_ALL (shouldn't happen).
2202 // This happens when called form buildMediaSessionService2List(...).
Jaewan Kim005e2bb2018-03-02 15:55:12 +09002203 // (b/73760382)
Sungsoo Lim375efa12018-03-02 10:17:08 +09002204 if (UserHandle.getUserId(token.getUid()) == userId
2205 || UserHandle.USER_ALL == userId) {
2206 tokens.add(token.toBundle());
2207 }
2208 }
2209
2210 for (SessionTokensListenerRecord record : mSessionTokensListeners) {
Jaewan Kim005e2bb2018-03-02 15:55:12 +09002211 // TODO(jaewan): Should userId be mapped through mFullUserIds? (b/73760382)
Sungsoo Lim375efa12018-03-02 10:17:08 +09002212 if (record.mUserId == userId || record.mUserId == UserHandle.USER_ALL) {
2213 try {
2214 record.mListener.onSessionTokensChanged(tokens);
2215 } catch (RemoteException e) {
2216 Log.w(TAG, "Failed to notify session tokens changed", e);
2217 }
2218 }
2219 }
2220 }
2221 }
2222
2223 private boolean addSessionRecordLocked(SessionToken2 token) {
2224 return addSessionRecordLocked(token, null);
2225 }
2226
2227 private boolean addSessionRecordLocked(SessionToken2 token, MediaController2 controller) {
2228 if (mSessionRecords.containsKey(token) && mSessionRecords.get(token) == controller) {
2229 // The key/value pair already exists, no need to update.
2230 return false;
2231 }
2232
2233 mSessionRecords.put(token, controller);
2234 return true;
2235 }
2236
2237 private boolean removeSessionRecordLocked(SessionToken2 token) {
2238 if (!mSessionRecords.containsKey(token)) {
2239 // The key is already removed, no need to remove.
2240 return false;
2241 }
2242
2243 mSessionRecords.remove(token);
2244 return true;
2245 }
RoboErik01fe6612014-02-13 14:19:04 -08002246}