blob: 1d6d1ed46f543c01d916b02a875f7b2d6b447b14 [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;
Julia Reynoldsb852e562017-06-06 16:14:18 -040022import android.app.INotificationManager;
RoboErik9a9d0b52014-05-20 14:53:39 -070023import android.app.KeyguardManager;
RoboErikb214efb2014-07-24 13:20:30 -070024import android.app.PendingIntent;
25import android.app.PendingIntent.CanceledException;
RoboErik9a9d0b52014-05-20 14:53:39 -070026import android.content.ActivityNotFoundException;
RoboErik8a2cfc32014-05-16 11:19:38 -070027import android.content.BroadcastReceiver;
RoboErike7880d82014-04-30 12:48:25 -070028import android.content.ComponentName;
RoboErik6f0e4dd2014-06-17 16:56:27 -070029import android.content.ContentResolver;
RoboErik01fe6612014-02-13 14:19:04 -080030import android.content.Context;
RoboErik8a2cfc32014-05-16 11:19:38 -070031import android.content.Intent;
RoboErika278ea72014-04-24 14:49:01 -070032import android.content.pm.PackageManager;
Jaewan Kimf7a77062018-01-27 01:34:24 +090033import android.content.pm.PackageManager.NameNotFoundException;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +090034import android.content.pm.ResolveInfo;
35import android.content.pm.ServiceInfo;
Jaewan Kima7dce192017-02-16 17:10:54 +090036import android.content.pm.UserInfo;
RoboErik7aef77b2014-08-08 15:56:54 -070037import android.database.ContentObserver;
RoboErik3c45c292014-07-08 16:47:31 -070038import android.media.AudioManager;
Sungsoo Lim875e6972017-11-03 02:22:35 +000039import android.media.AudioPlaybackConfiguration;
RoboErik94c716e2014-09-14 13:54:31 -070040import android.media.AudioSystem;
RoboErikb69ffd42014-05-30 14:57:59 -070041import android.media.IAudioService;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +090042import android.media.IMediaSession2;
RoboErik19c95182014-06-23 15:38:48 -070043import android.media.IRemoteVolumeController;
Jaewan Kimbcecf312018-01-23 19:30:42 +090044import android.media.MediaLibraryService2;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +090045import android.media.MediaSessionService2;
Jaewan Kim04de5de2018-01-25 02:24:03 +090046import android.media.SessionToken2;
RoboErik2e7a9162014-06-04 16:53:45 -070047import android.media.session.IActiveSessionsListener;
Jaewan Kimbd16f452017-02-03 16:21:38 +090048import android.media.session.ICallback;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080049import android.media.session.IOnMediaKeyListener;
Jaewan Kim50269362016-12-23 11:22:02 +090050import android.media.session.IOnVolumeKeyLongPressListener;
RoboErik07c70772014-03-20 13:33:52 -070051import android.media.session.ISession;
52import android.media.session.ISessionCallback;
53import android.media.session.ISessionManager;
Jeff Browndba34ba2014-06-24 20:46:03 -070054import android.media.session.MediaSession;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080055import android.media.session.MediaSessionManager;
RoboErik7aef77b2014-08-08 15:56:54 -070056import android.net.Uri;
RoboErik01fe6612014-02-13 14:19:04 -080057import android.os.Binder;
RoboErik8a2cfc32014-05-16 11:19:38 -070058import android.os.Bundle;
RoboErik8ae0f342014-02-24 18:02:08 -080059import android.os.Handler;
RoboErike7880d82014-04-30 12:48:25 -070060import android.os.IBinder;
RoboErik2e7a9162014-06-04 16:53:45 -070061import android.os.Message;
RoboErik8a2cfc32014-05-16 11:19:38 -070062import android.os.PowerManager;
Jaewan Kim8f729082016-06-21 12:36:26 +090063import android.os.Process;
RoboErik01fe6612014-02-13 14:19:04 -080064import android.os.RemoteException;
RoboErik8a2cfc32014-05-16 11:19:38 -070065import android.os.ResultReceiver;
RoboErikb69ffd42014-05-30 14:57:59 -070066import android.os.ServiceManager;
RoboErike7880d82014-04-30 12:48:25 -070067import android.os.UserHandle;
Jaewan Kim8f729082016-06-21 12:36:26 +090068import android.os.UserManager;
RoboErike7880d82014-04-30 12:48:25 -070069import android.provider.Settings;
RoboErik9a9d0b52014-05-20 14:53:39 -070070import android.speech.RecognizerIntent;
RoboErik01fe6612014-02-13 14:19:04 -080071import android.text.TextUtils;
72import android.util.Log;
Jeff Brown38d3feb2015-03-19 18:26:30 -070073import android.util.Slog;
RoboErik4646d282014-05-13 10:13:04 -070074import android.util.SparseArray;
Jaewan Kima7dce192017-02-16 17:10:54 +090075import android.util.SparseIntArray;
RoboErik8a2cfc32014-05-16 11:19:38 -070076import android.view.KeyEvent;
Jaewan Kimd61a87b2017-02-17 23:14:10 +090077import android.view.ViewConfiguration;
RoboErik01fe6612014-02-13 14:19:04 -080078
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060079import com.android.internal.util.DumpUtils;
RoboErik01fe6612014-02-13 14:19:04 -080080import com.android.server.SystemService;
RoboErika278ea72014-04-24 14:49:01 -070081import com.android.server.Watchdog;
82import com.android.server.Watchdog.Monitor;
RoboErik01fe6612014-02-13 14:19:04 -080083
RoboErika278ea72014-04-24 14:49:01 -070084import java.io.FileDescriptor;
85import java.io.PrintWriter;
RoboErik01fe6612014-02-13 14:19:04 -080086import java.util.ArrayList;
RoboErike7880d82014-04-30 12:48:25 -070087import java.util.List;
RoboErik01fe6612014-02-13 14:19:04 -080088
89/**
90 * System implementation of MediaSessionManager
91 */
RoboErika278ea72014-04-24 14:49:01 -070092public class MediaSessionService extends SystemService implements Monitor {
RoboErik01fe6612014-02-13 14:19:04 -080093 private static final String TAG = "MediaSessionService";
Jaewan Kim92dea332017-02-02 11:52:08 +090094 static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jaewan Kim50269362016-12-23 11:22:02 +090095 // Leave log for key event always.
96 private static final boolean DEBUG_KEY_EVENT = true;
RoboErik01fe6612014-02-13 14:19:04 -080097
RoboErik418c10c2014-05-19 09:25:25 -070098 private static final int WAKELOCK_TIMEOUT = 5000;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080099 private static final int MEDIA_KEY_LISTENER_TIMEOUT = 1000;
RoboErik418c10c2014-05-19 09:25:25 -0700100
RoboErik01fe6612014-02-13 14:19:04 -0800101 private final SessionManagerImpl mSessionManagerImpl;
102
Jaewan Kima7dce192017-02-16 17:10:54 +0900103 // Keeps the full user id for each user.
104 private final SparseIntArray mFullUserIds = new SparseIntArray();
105 private final SparseArray<FullUserRecord> mUserRecords = new SparseArray<FullUserRecord>();
RoboErik2e7a9162014-06-04 16:53:45 -0700106 private final ArrayList<SessionsListenerRecord> mSessionsListeners
107 = new ArrayList<SessionsListenerRecord>();
RoboErik01fe6612014-02-13 14:19:04 -0800108 private final Object mLock = new Object();
RoboErik2e7a9162014-06-04 16:53:45 -0700109 private final MessageHandler mHandler = new MessageHandler();
RoboErik8a2cfc32014-05-16 11:19:38 -0700110 private final PowerManager.WakeLock mMediaEventWakeLock;
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900111 private final int mLongPressTimeout;
RoboErik01fe6612014-02-13 14:19:04 -0800112
RoboErik9a9d0b52014-05-20 14:53:39 -0700113 private KeyguardManager mKeyguardManager;
RoboErikb69ffd42014-05-30 14:57:59 -0700114 private IAudioService mAudioService;
RoboErik6f0e4dd2014-06-17 16:56:27 -0700115 private ContentResolver mContentResolver;
RoboErik7aef77b2014-08-08 15:56:54 -0700116 private SettingsObserver mSettingsObserver;
Julia Reynoldsb852e562017-06-06 16:14:18 -0400117 private INotificationManager mNotificationManager;
Jaewan Kimfdb612e2017-07-01 09:23:41 +0900118 private boolean mHasFeatureLeanback;
RoboErik9a9d0b52014-05-20 14:53:39 -0700119
Jaewan Kima7dce192017-02-16 17:10:54 +0900120 // The FullUserRecord of the current users. (i.e. The foreground user that isn't a profile)
121 // It's always not null after the MediaSessionService is started.
122 private FullUserRecord mCurrentFullUserRecord;
123 private MediaSessionRecord mGlobalPrioritySession;
Sungsoo Lim875e6972017-11-03 02:22:35 +0000124 private AudioPlayerStateMonitor mAudioPlayerStateMonitor;
RoboErike7880d82014-04-30 12:48:25 -0700125
RoboErik19c95182014-06-23 15:38:48 -0700126 // Used to notify system UI when remote volume was changed. TODO find a
127 // better way to handle this.
128 private IRemoteVolumeController mRvc;
129
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900130 // MediaSession2 support
131 // TODO(jaewan): Support multi-user and managed profile.
132 // TODO(jaewan): Make it priority list for handling volume/media key.
133 private final List<MediaSession2Record> mSessions = new ArrayList<>();
134
135 private final MediaSession2Record.SessionDestroyedListener mSessionDestroyedListener =
Jaewan Kimf7a77062018-01-27 01:34:24 +0900136 (record) -> {
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900137 synchronized (mLock) {
Jaewan Kimf7a77062018-01-27 01:34:24 +0900138 destroySessionLocked(record);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900139 }
140 };
141
RoboErik01fe6612014-02-13 14:19:04 -0800142 public MediaSessionService(Context context) {
143 super(context);
144 mSessionManagerImpl = new SessionManagerImpl();
RoboErik8a2cfc32014-05-16 11:19:38 -0700145 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
146 mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900147 mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
Julia Reynoldsb852e562017-06-06 16:14:18 -0400148 mNotificationManager = INotificationManager.Stub.asInterface(
149 ServiceManager.getService(Context.NOTIFICATION_SERVICE));
RoboErik01fe6612014-02-13 14:19:04 -0800150 }
151
152 @Override
153 public void onStart() {
154 publishBinderService(Context.MEDIA_SESSION_SERVICE, mSessionManagerImpl);
RoboErika278ea72014-04-24 14:49:01 -0700155 Watchdog.getInstance().addMonitor(this);
RoboErik9a9d0b52014-05-20 14:53:39 -0700156 mKeyguardManager =
157 (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
RoboErikb69ffd42014-05-30 14:57:59 -0700158 mAudioService = getAudioService();
Sungsoo Lim875e6972017-11-03 02:22:35 +0000159 mAudioPlayerStateMonitor = AudioPlayerStateMonitor.getInstance();
160 mAudioPlayerStateMonitor.registerListener(
Sungsoo Lim2afdbc42017-11-01 13:45:59 +0900161 (config, isRemoved) -> {
162 if (isRemoved || !config.isActive() || config.getPlayerType()
163 == AudioPlaybackConfiguration.PLAYER_TYPE_JAM_SOUNDPOOL) {
164 return;
Jaewan Kim92dea332017-02-02 11:52:08 +0900165 }
Sungsoo Lim2afdbc42017-11-01 13:45:59 +0900166 synchronized (mLock) {
167 FullUserRecord user = getFullUserRecordLocked(
168 UserHandle.getUserId(config.getClientUid()));
169 if (user != null) {
170 user.mPriorityStack.updateMediaButtonSessionIfNeeded();
171 }
172 }
173 }, null /* handler */);
Sungsoo Lim875e6972017-11-03 02:22:35 +0000174 mAudioPlayerStateMonitor.registerSelfIntoAudioServiceIfNeeded(mAudioService);
RoboErik6f0e4dd2014-06-17 16:56:27 -0700175 mContentResolver = getContext().getContentResolver();
RoboErik7aef77b2014-08-08 15:56:54 -0700176 mSettingsObserver = new SettingsObserver();
177 mSettingsObserver.observe();
Jaewan Kimfdb612e2017-07-01 09:23:41 +0900178 mHasFeatureLeanback = getContext().getPackageManager().hasSystemFeature(
179 PackageManager.FEATURE_LEANBACK);
RoboErikc8f92d12015-01-05 16:48:07 -0800180
181 updateUser();
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900182
183 // TODO(jaewan): Query per users
184 // TODO(jaewan): Add listener to know changes in list of services.
185 // Refer TvInputManagerService.registerBroadcastReceivers()
186 buildMediaSessionService2List();
RoboErikb69ffd42014-05-30 14:57:59 -0700187 }
188
189 private IAudioService getAudioService() {
190 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
191 return IAudioService.Stub.asInterface(b);
RoboErik07c70772014-03-20 13:33:52 -0700192 }
193
Jaewan Kima7dce192017-02-16 17:10:54 +0900194 private boolean isGlobalPriorityActiveLocked() {
195 return mGlobalPrioritySession != null && mGlobalPrioritySession.isActive();
196 }
197
RoboErika8f95142014-05-05 14:23:49 -0700198 public void updateSession(MediaSessionRecord record) {
RoboErike7880d82014-04-30 12:48:25 -0700199 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900200 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
Jaewan Kim101b4d52017-05-18 13:23:11 +0900201 if (user == null) {
202 Log.w(TAG, "Unknown session updated. Ignoring.");
RoboErik4646d282014-05-13 10:13:04 -0700203 return;
204 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900205 if ((record.getFlags() & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
Jaewan Kim101b4d52017-05-18 13:23:11 +0900206 if (DEBUG_KEY_EVENT) {
207 Log.d(TAG, "Global priority session is updated, active=" + record.isActive());
208 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900209 user.pushAddressedPlayerChangedLocked();
Jaewan Kim101b4d52017-05-18 13:23:11 +0900210 } else {
211 if (!user.mPriorityStack.contains(record)) {
212 Log.w(TAG, "Unknown session updated. Ignoring.");
213 return;
214 }
215 user.mPriorityStack.onSessionStateChange(record);
Jaewan Kima7dce192017-02-16 17:10:54 +0900216 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900217 mHandler.postSessionsChanged(record.getUserId());
RoboErike7880d82014-04-30 12:48:25 -0700218 }
219 }
220
Jaewan Kimfa85b602017-10-10 16:49:58 +0900221 public void setGlobalPrioritySession(MediaSessionRecord record) {
222 synchronized (mLock) {
223 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
224 if (mGlobalPrioritySession != record) {
225 Log.d(TAG, "Global priority session is changed from " + mGlobalPrioritySession
226 + " to " + record);
227 mGlobalPrioritySession = record;
228 if (user != null && user.mPriorityStack.contains(record)) {
229 // Handle the global priority session separately.
230 // Otherwise, it can be the media button session regardless of the active state
231 // because it or other system components might have been the lastly played media
232 // app.
233 user.mPriorityStack.removeSession(record);
234 }
235 }
236 }
237 }
238
Jaewan Kim101b4d52017-05-18 13:23:11 +0900239 private List<MediaSessionRecord> getActiveSessionsLocked(int userId) {
Jaewan Kimda74a152017-10-03 23:58:11 +0900240 List<MediaSessionRecord> records = new ArrayList<>();
Jaewan Kim101b4d52017-05-18 13:23:11 +0900241 if (userId == UserHandle.USER_ALL) {
Jaewan Kim101b4d52017-05-18 13:23:11 +0900242 int size = mUserRecords.size();
243 for (int i = 0; i < size; i++) {
244 records.addAll(mUserRecords.valueAt(i).mPriorityStack.getActiveSessions(userId));
245 }
246 } else {
247 FullUserRecord user = getFullUserRecordLocked(userId);
248 if (user == null) {
249 Log.w(TAG, "getSessions failed. Unknown user " + userId);
Jaewan Kimda74a152017-10-03 23:58:11 +0900250 return records;
Jaewan Kim101b4d52017-05-18 13:23:11 +0900251 }
Jaewan Kimda74a152017-10-03 23:58:11 +0900252 records.addAll(user.mPriorityStack.getActiveSessions(userId));
Jaewan Kim101b4d52017-05-18 13:23:11 +0900253 }
254
255 // Return global priority session at the first whenever it's asked.
256 if (isGlobalPriorityActiveLocked()
257 && (userId == UserHandle.USER_ALL
258 || userId == mGlobalPrioritySession.getUserId())) {
259 records.add(0, mGlobalPrioritySession);
260 }
261 return records;
262 }
263
RoboErik9c5b7cb2015-01-15 15:09:09 -0800264 /**
Hyundo Moona055f132017-01-13 15:31:06 +0900265 * Tells the system UI that volume has changed on an active remote session.
RoboErik9c5b7cb2015-01-15 15:09:09 -0800266 */
267 public void notifyRemoteVolumeChanged(int flags, MediaSessionRecord session) {
Hyundo Moona055f132017-01-13 15:31:06 +0900268 if (mRvc == null || !session.isActive()) {
RoboErik9c5b7cb2015-01-15 15:09:09 -0800269 return;
270 }
271 try {
272 mRvc.remoteVolumeChanged(session.getControllerBinder(), flags);
273 } catch (Exception e) {
274 Log.wtf(TAG, "Error sending volume change to system UI.", e);
275 }
276 }
277
Jaewan Kim92dea332017-02-02 11:52:08 +0900278 public void onSessionPlaystateChanged(MediaSessionRecord record, int oldState, int newState) {
RoboErika8f95142014-05-05 14:23:49 -0700279 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900280 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
281 if (user == null || !user.mPriorityStack.contains(record)) {
RoboErik4646d282014-05-13 10:13:04 -0700282 Log.d(TAG, "Unknown session changed playback state. Ignoring.");
283 return;
284 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900285 user.mPriorityStack.onPlaystateChanged(record, oldState, newState);
RoboErika8f95142014-05-05 14:23:49 -0700286 }
287 }
288
RoboErik19c95182014-06-23 15:38:48 -0700289 public void onSessionPlaybackTypeChanged(MediaSessionRecord record) {
290 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900291 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
292 if (user == null || !user.mPriorityStack.contains(record)) {
RoboErik19c95182014-06-23 15:38:48 -0700293 Log.d(TAG, "Unknown session changed playback type. Ignoring.");
294 return;
295 }
296 pushRemoteVolumeUpdateLocked(record.getUserId());
297 }
298 }
299
RoboErika278ea72014-04-24 14:49:01 -0700300 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900301 public void onStartUser(int userId) {
302 if (DEBUG) Log.d(TAG, "onStartUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700303 updateUser();
304 }
305
306 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900307 public void onSwitchUser(int userId) {
308 if (DEBUG) Log.d(TAG, "onSwitchUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700309 updateUser();
310 }
311
312 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900313 public void onStopUser(int userId) {
314 if (DEBUG) Log.d(TAG, "onStopUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700315 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900316 FullUserRecord user = getFullUserRecordLocked(userId);
RoboErik4646d282014-05-13 10:13:04 -0700317 if (user != null) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900318 if (user.mFullUserId == userId) {
319 user.destroySessionsForUserLocked(UserHandle.USER_ALL);
320 mUserRecords.remove(userId);
321 } else {
322 user.destroySessionsForUserLocked(userId);
323 }
RoboErik4646d282014-05-13 10:13:04 -0700324 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900325 updateUser();
RoboErik4646d282014-05-13 10:13:04 -0700326 }
327 }
328
329 @Override
RoboErika278ea72014-04-24 14:49:01 -0700330 public void monitor() {
331 synchronized (mLock) {
332 // Check for deadlock
333 }
334 }
335
RoboErik4646d282014-05-13 10:13:04 -0700336 protected void enforcePhoneStatePermission(int pid, int uid) {
337 if (getContext().checkPermission(android.Manifest.permission.MODIFY_PHONE_STATE, pid, uid)
338 != PackageManager.PERMISSION_GRANTED) {
339 throw new SecurityException("Must hold the MODIFY_PHONE_STATE permission.");
340 }
341 }
342
RoboErik01fe6612014-02-13 14:19:04 -0800343 void sessionDied(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700344 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800345 destroySessionLocked(session);
346 }
347 }
348
349 void destroySession(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700350 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800351 destroySessionLocked(session);
352 }
353 }
354
RoboErik4646d282014-05-13 10:13:04 -0700355 private void updateUser() {
356 synchronized (mLock) {
Jaewan Kim8f729082016-06-21 12:36:26 +0900357 UserManager manager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
Jaewan Kima7dce192017-02-16 17:10:54 +0900358 mFullUserIds.clear();
359 List<UserInfo> allUsers = manager.getUsers();
360 if (allUsers != null) {
361 for (UserInfo userInfo : allUsers) {
362 if (userInfo.isManagedProfile()) {
363 mFullUserIds.put(userInfo.id, userInfo.profileGroupId);
364 } else {
365 mFullUserIds.put(userInfo.id, userInfo.id);
366 if (mUserRecords.get(userInfo.id) == null) {
367 mUserRecords.put(userInfo.id, new FullUserRecord(userInfo.id));
368 }
369 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900370 }
RoboErik4646d282014-05-13 10:13:04 -0700371 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900372 // Ensure that the current full user exists.
373 int currentFullUserId = ActivityManager.getCurrentUser();
374 mCurrentFullUserRecord = mUserRecords.get(currentFullUserId);
375 if (mCurrentFullUserRecord == null) {
376 Log.w(TAG, "Cannot find FullUserInfo for the current user " + currentFullUserId);
377 mCurrentFullUserRecord = new FullUserRecord(currentFullUserId);
378 mUserRecords.put(currentFullUserId, mCurrentFullUserRecord);
379 }
380 mFullUserIds.put(currentFullUserId, currentFullUserId);
RoboErik4646d282014-05-13 10:13:04 -0700381 }
382 }
383
RoboErik7aef77b2014-08-08 15:56:54 -0700384 private void updateActiveSessionListeners() {
385 synchronized (mLock) {
386 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
387 SessionsListenerRecord listener = mSessionsListeners.get(i);
388 try {
389 enforceMediaPermissions(listener.mComponentName, listener.mPid, listener.mUid,
390 listener.mUserId);
391 } catch (SecurityException e) {
392 Log.i(TAG, "ActiveSessionsListener " + listener.mComponentName
393 + " is no longer authorized. Disconnecting.");
394 mSessionsListeners.remove(i);
395 try {
396 listener.mListener
397 .onActiveSessionsChanged(new ArrayList<MediaSession.Token>());
398 } catch (Exception e1) {
399 // ignore
400 }
401 }
402 }
403 }
404 }
405
RoboErik4646d282014-05-13 10:13:04 -0700406 /*
407 * When a session is removed several things need to happen.
408 * 1. We need to remove it from the relevant user.
409 * 2. We need to remove it from the priority stack.
410 * 3. We need to remove it from all sessions.
411 * 4. If this is the system priority session we need to clear it.
412 * 5. We need to unlink to death from the cb binder
413 * 6. We need to tell the session to do any final cleanup (onDestroy)
414 */
RoboErik01fe6612014-02-13 14:19:04 -0800415 private void destroySessionLocked(MediaSessionRecord session) {
Insun Kang30be970a2015-11-26 15:35:44 +0900416 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900417 Log.d(TAG, "Destroying " + session);
Insun Kang30be970a2015-11-26 15:35:44 +0900418 }
Jaewan Kim101b4d52017-05-18 13:23:11 +0900419 FullUserRecord user = getFullUserRecordLocked(session.getUserId());
Jaewan Kima7dce192017-02-16 17:10:54 +0900420 if (mGlobalPrioritySession == session) {
421 mGlobalPrioritySession = null;
Jaewan Kim92dea332017-02-02 11:52:08 +0900422 if (session.isActive() && user != null) {
423 user.pushAddressedPlayerChangedLocked();
424 }
Jaewan Kim101b4d52017-05-18 13:23:11 +0900425 } else {
426 if (user != null) {
427 user.mPriorityStack.removeSession(session);
428 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900429 }
RoboErik4646d282014-05-13 10:13:04 -0700430
431 try {
432 session.getCallback().asBinder().unlinkToDeath(session, 0);
433 } catch (Exception e) {
434 // ignore exceptions while destroying a session.
435 }
436 session.onDestroy();
Jaewan Kim92dea332017-02-02 11:52:08 +0900437 mHandler.postSessionsChanged(session.getUserId());
RoboErik01fe6612014-02-13 14:19:04 -0800438 }
439
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900440 private void buildMediaSessionService2List() {
441 if (DEBUG) {
442 Log.d(TAG, "buildMediaSessionService2List");
443 }
444
445 // TODO(jaewan): Query per users.
Jaewan Kimf7a77062018-01-27 01:34:24 +0900446 // TODO(jaewan): Similar codes are also at the updatable. Can't we share codes?
447 PackageManager manager = getContext().getPackageManager();
Jaewan Kimbcecf312018-01-23 19:30:42 +0900448 List<ResolveInfo> services = new ArrayList<>();
449 // If multiple actions are declared for a service, browser gets higher priority.
Jaewan Kimf7a77062018-01-27 01:34:24 +0900450 List<ResolveInfo> libraryServices = manager.queryIntentServices(
Jaewan Kimbcecf312018-01-23 19:30:42 +0900451 new Intent(MediaLibraryService2.SERVICE_INTERFACE), PackageManager.GET_META_DATA);
452 if (libraryServices != null) {
453 services.addAll(libraryServices);
454 }
Jaewan Kimf7a77062018-01-27 01:34:24 +0900455 List<ResolveInfo> sessionServices = manager.queryIntentServices(
Jaewan Kimbcecf312018-01-23 19:30:42 +0900456 new Intent(MediaSessionService2.SERVICE_INTERFACE), PackageManager.GET_META_DATA);
457 if (sessionServices != null) {
458 services.addAll(sessionServices);
459 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900460 synchronized (mLock) {
461 mSessions.clear();
462 if (services == null) {
463 return;
464 }
465 for (int i = 0; i < services.size(); i++) {
466 if (services.get(i) == null || services.get(i).serviceInfo == null) {
467 continue;
468 }
469 ServiceInfo serviceInfo = services.get(i).serviceInfo;
Jaewan Kimf7a77062018-01-27 01:34:24 +0900470 int uid;
471 try {
472 uid = manager.getPackageUid(serviceInfo.packageName,
473 PackageManager.GET_META_DATA);
474 } catch (NameNotFoundException e) {
475 continue;
476 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900477 String id = (serviceInfo.metaData != null) ? serviceInfo.metaData.getString(
478 MediaSessionService2.SERVICE_META_DATA) : null;
479 // Do basic sanity check
480 // TODO(jaewan): also santity check if it's protected with the system|privileged
481 // permission
Jaewan Kimf7a77062018-01-27 01:34:24 +0900482 boolean conflict = (getSessionRecordLocked(uid, serviceInfo.name, id) != null);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900483 if (conflict) {
484 Log.w(TAG, serviceInfo.packageName + " contains multiple"
485 + " MediaSessionService2s declared in the manifest with"
486 + " the same ID=" + id + ". Ignoring "
487 + serviceInfo.packageName + "/" + serviceInfo.name);
488 } else {
Jaewan Kimbcecf312018-01-23 19:30:42 +0900489 int type = (libraryServices.contains(services.get(i)))
Jaewan Kimf7a77062018-01-27 01:34:24 +0900490 ? SessionToken2.TYPE_LIBRARY_SERVICE
491 : SessionToken2.TYPE_SESSION_SERVICE;
492 SessionToken2 token = new SessionToken2(getContext(), uid, type,
493 serviceInfo.packageName, serviceInfo.name, id, null);
494 MediaSession2Record record = new MediaSession2Record(getContext(),
495 token, mSessionDestroyedListener);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900496 mSessions.add(record);
497 }
498 }
499 }
500 if (DEBUG) {
501 Log.d(TAG, "Found " + mSessions.size() + " session services");
502 for (int i = 0; i < mSessions.size(); i++) {
503 Log.d(TAG, " " + mSessions.get(i).getToken());
504 }
505 }
506 }
507
Jaewan Kimf7a77062018-01-27 01:34:24 +0900508 private MediaSession2Record getSessionRecordLocked(int uid, String packageName, String id) {
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900509 for (int i = 0; i < mSessions.size(); i++) {
Jaewan Kimf7a77062018-01-27 01:34:24 +0900510 SessionToken2 token = mSessions.get(i).getToken();
511 if (token.getUid() == uid && token.getPackageName().equals(packageName)
512 && token.getId().equals(id)) {
513 return mSessions.get(i);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +0900514 }
515 }
516 return null;
517 }
518
Jaewan Kimf7a77062018-01-27 01:34:24 +0900519 private void destroySessionLocked(MediaSession2Record record) {
520 if (DEBUG) {
521 Log.d(TAG, record.toString() + " becomes inactive");
522 }
523 record.onSessionDestroyed();
524 if (record.getToken().getType() == TYPE_SESSION) {
525 mSessions.remove(record);
526 }
527 }
528
RoboErik01fe6612014-02-13 14:19:04 -0800529 private void enforcePackageName(String packageName, int uid) {
530 if (TextUtils.isEmpty(packageName)) {
531 throw new IllegalArgumentException("packageName may not be empty");
532 }
533 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
534 final int packageCount = packages.length;
535 for (int i = 0; i < packageCount; i++) {
536 if (packageName.equals(packages[i])) {
537 return;
538 }
539 }
540 throw new IllegalArgumentException("packageName is not owned by the calling process");
541 }
542
RoboErike7880d82014-04-30 12:48:25 -0700543 /**
544 * Checks a caller's authorization to register an IRemoteControlDisplay.
545 * Authorization is granted if one of the following is true:
546 * <ul>
547 * <li>the caller has android.Manifest.permission.MEDIA_CONTENT_CONTROL
548 * permission</li>
RoboErika5b02322014-05-07 17:05:49 -0700549 * <li>the caller's listener is one of the enabled notification listeners
550 * for the caller's user</li>
RoboErike7880d82014-04-30 12:48:25 -0700551 * </ul>
552 */
RoboErika5b02322014-05-07 17:05:49 -0700553 private void enforceMediaPermissions(ComponentName compName, int pid, int uid,
554 int resolvedUserId) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500555 if (isCurrentVolumeController(uid, pid)) return;
RoboErike7880d82014-04-30 12:48:25 -0700556 if (getContext()
557 .checkPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
558 != PackageManager.PERMISSION_GRANTED
RoboErika5b02322014-05-07 17:05:49 -0700559 && !isEnabledNotificationListener(compName, UserHandle.getUserId(uid),
560 resolvedUserId)) {
RoboErike7880d82014-04-30 12:48:25 -0700561 throw new SecurityException("Missing permission to control media.");
562 }
563 }
564
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500565 private boolean isCurrentVolumeController(int uid, int pid) {
566 return getContext().checkPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
567 pid, uid) == PackageManager.PERMISSION_GRANTED;
John Spurlockbe19ed02015-02-22 10:57:55 -0500568 }
569
570 private void enforceSystemUiPermission(String action, int pid, int uid) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500571 if (!isCurrentVolumeController(uid, pid)) {
RoboErik19c95182014-06-23 15:38:48 -0700572 throw new SecurityException("Only system ui may " + action);
573 }
574 }
575
RoboErika5b02322014-05-07 17:05:49 -0700576 /**
577 * This checks if the component is an enabled notification listener for the
578 * specified user. Enabled components may only operate on behalf of the user
579 * they're running as.
580 *
581 * @param compName The component that is enabled.
582 * @param userId The user id of the caller.
583 * @param forUserId The user id they're making the request on behalf of.
584 * @return True if the component is enabled, false otherwise
585 */
586 private boolean isEnabledNotificationListener(ComponentName compName, int userId,
587 int forUserId) {
588 if (userId != forUserId) {
589 // You may not access another user's content as an enabled listener.
590 return false;
591 }
RoboErik51fa6bc2014-06-20 14:59:58 -0700592 if (DEBUG) {
593 Log.d(TAG, "Checking if enabled notification listener " + compName);
594 }
RoboErike7880d82014-04-30 12:48:25 -0700595 if (compName != null) {
Julia Reynoldsb852e562017-06-06 16:14:18 -0400596 try {
597 return mNotificationManager.isNotificationListenerAccessGrantedForUser(
598 compName, userId);
599 } catch(RemoteException e) {
600 Log.w(TAG, "Dead NotificationManager in isEnabledNotificationListener", e);
RoboErike7880d82014-04-30 12:48:25 -0700601 }
602 }
603 return false;
604 }
605
RoboErika5b02322014-05-07 17:05:49 -0700606 private MediaSessionRecord createSessionInternal(int callerPid, int callerUid, int userId,
RoboErik4646d282014-05-13 10:13:04 -0700607 String callerPackageName, ISessionCallback cb, String tag) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800608 synchronized (mLock) {
RoboErika5b02322014-05-07 17:05:49 -0700609 return createSessionLocked(callerPid, callerUid, userId, callerPackageName, cb, tag);
RoboErik01fe6612014-02-13 14:19:04 -0800610 }
611 }
612
RoboErik4646d282014-05-13 10:13:04 -0700613 /*
614 * When a session is created the following things need to happen.
RoboErik8a2cfc32014-05-16 11:19:38 -0700615 * 1. Its callback binder needs a link to death
RoboErik4646d282014-05-13 10:13:04 -0700616 * 2. It needs to be added to all sessions.
617 * 3. It needs to be added to the priority stack.
618 * 4. It needs to be added to the relevant user record.
619 */
RoboErika5b02322014-05-07 17:05:49 -0700620 private MediaSessionRecord createSessionLocked(int callerPid, int callerUid, int userId,
621 String callerPackageName, ISessionCallback cb, String tag) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900622 FullUserRecord user = getFullUserRecordLocked(userId);
Dongwon Kang8cf39c52016-07-29 13:20:39 -0700623 if (user == null) {
624 Log.wtf(TAG, "Request from invalid user: " + userId);
625 throw new RuntimeException("Session request from invalid user.");
626 }
627
RoboErika5b02322014-05-07 17:05:49 -0700628 final MediaSessionRecord session = new MediaSessionRecord(callerPid, callerUid, userId,
Jaewan Kim92dea332017-02-02 11:52:08 +0900629 callerPackageName, cb, tag, this, mHandler.getLooper());
RoboErik01fe6612014-02-13 14:19:04 -0800630 try {
631 cb.asBinder().linkToDeath(session, 0);
632 } catch (RemoteException e) {
633 throw new RuntimeException("Media Session owner died prematurely.", e);
634 }
RoboErik4646d282014-05-13 10:13:04 -0700635
Jaewan Kim101b4d52017-05-18 13:23:11 +0900636 user.mPriorityStack.addSession(session);
Jaewan Kim92dea332017-02-02 11:52:08 +0900637 mHandler.postSessionsChanged(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700638
RoboErik01fe6612014-02-13 14:19:04 -0800639 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900640 Log.d(TAG, "Created session for " + callerPackageName + " with tag " + tag);
RoboErik01fe6612014-02-13 14:19:04 -0800641 }
642 return session;
643 }
644
RoboErik2e7a9162014-06-04 16:53:45 -0700645 private int findIndexOfSessionsListenerLocked(IActiveSessionsListener listener) {
646 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
RoboErika08adb242014-11-21 18:28:18 -0800647 if (mSessionsListeners.get(i).mListener.asBinder() == listener.asBinder()) {
RoboErik2e7a9162014-06-04 16:53:45 -0700648 return i;
649 }
650 }
651 return -1;
652 }
653
RoboErik2e7a9162014-06-04 16:53:45 -0700654 private void pushSessionsChanged(int userId) {
655 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900656 FullUserRecord user = getFullUserRecordLocked(userId);
657 if (user == null) {
658 Log.w(TAG, "pushSessionsChanged failed. No user with id=" + userId);
659 return;
660 }
Jaewan Kim101b4d52017-05-18 13:23:11 +0900661 List<MediaSessionRecord> records = getActiveSessionsLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700662 int size = records.size();
Jeff Browndba34ba2014-06-24 20:46:03 -0700663 ArrayList<MediaSession.Token> tokens = new ArrayList<MediaSession.Token>();
RoboErik2e7a9162014-06-04 16:53:45 -0700664 for (int i = 0; i < size; i++) {
Jeff Browndba34ba2014-06-24 20:46:03 -0700665 tokens.add(new MediaSession.Token(records.get(i).getControllerBinder()));
RoboErik2e7a9162014-06-04 16:53:45 -0700666 }
RoboErik19c95182014-06-23 15:38:48 -0700667 pushRemoteVolumeUpdateLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700668 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
669 SessionsListenerRecord record = mSessionsListeners.get(i);
670 if (record.mUserId == UserHandle.USER_ALL || record.mUserId == userId) {
671 try {
672 record.mListener.onActiveSessionsChanged(tokens);
673 } catch (RemoteException e) {
674 Log.w(TAG, "Dead ActiveSessionsListener in pushSessionsChanged, removing",
675 e);
676 mSessionsListeners.remove(i);
677 }
678 }
679 }
680 }
681 }
682
RoboErik19c95182014-06-23 15:38:48 -0700683 private void pushRemoteVolumeUpdateLocked(int userId) {
684 if (mRvc != null) {
685 try {
Jaewan Kima7dce192017-02-16 17:10:54 +0900686 FullUserRecord user = getFullUserRecordLocked(userId);
687 if (user == null) {
688 Log.w(TAG, "pushRemoteVolumeUpdateLocked failed. No user with id=" + userId);
689 return;
690 }
691 MediaSessionRecord record = user.mPriorityStack.getDefaultRemoteSession(userId);
RoboErik19c95182014-06-23 15:38:48 -0700692 mRvc.updateRemoteController(record == null ? null : record.getControllerBinder());
693 } catch (RemoteException e) {
694 Log.wtf(TAG, "Error sending default remote volume to sys ui.", e);
695 }
696 }
697 }
698
Jaewan Kim92dea332017-02-02 11:52:08 +0900699 /**
700 * Called when the media button receiver for the {@param record} is changed.
701 *
702 * @param record the media session whose media button receiver is updated.
703 */
704 public void onMediaButtonReceiverChanged(MediaSessionRecord record) {
705 synchronized (mLock) {
706 FullUserRecord user = getFullUserRecordLocked(record.getUserId());
707 MediaSessionRecord mediaButtonSession =
708 user.mPriorityStack.getMediaButtonSession();
709 if (record == mediaButtonSession) {
710 user.rememberMediaButtonReceiverLocked(mediaButtonSession);
711 }
712 }
713 }
714
Jaewan Kim50269362016-12-23 11:22:02 +0900715 private String getCallingPackageName(int uid) {
716 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
717 if (packages != null && packages.length > 0) {
718 return packages[0];
719 }
720 return "";
721 }
722
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900723 private void dispatchVolumeKeyLongPressLocked(KeyEvent keyEvent) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900724 try {
Jaewan Kima7dce192017-02-16 17:10:54 +0900725 mCurrentFullUserRecord.mOnVolumeKeyLongPressListener.onVolumeKeyLongPress(keyEvent);
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900726 } catch (RemoteException e) {
727 Log.w(TAG, "Failed to send " + keyEvent + " to volume key long-press listener");
728 }
729 }
730
Jaewan Kima7dce192017-02-16 17:10:54 +0900731 private FullUserRecord getFullUserRecordLocked(int userId) {
732 int fullUserId = mFullUserIds.get(userId, -1);
733 if (fullUserId < 0) {
734 return null;
735 }
736 return mUserRecords.get(fullUserId);
737 }
738
RoboErik4646d282014-05-13 10:13:04 -0700739 /**
Jaewan Kima7dce192017-02-16 17:10:54 +0900740 * Information about a full user and its corresponding managed profiles.
741 *
742 * <p>Since the full user runs together with its managed profiles, a user wouldn't differentiate
743 * them when he/she presses a media/volume button. So keeping media sessions for them in one
744 * place makes more sense and increases the readability.</p>
745 * <p>The contents of this object is guarded by {@link #mLock}.
RoboErik4646d282014-05-13 10:13:04 -0700746 */
Jaewan Kim92dea332017-02-02 11:52:08 +0900747 final class FullUserRecord implements MediaSessionStack.OnMediaButtonSessionChangedListener {
Jaewan Kima7dce192017-02-16 17:10:54 +0900748 private static final String COMPONENT_NAME_USER_ID_DELIM = ",";
749 private final int mFullUserId;
Jaewan Kim92dea332017-02-02 11:52:08 +0900750 private final MediaSessionStack mPriorityStack;
RoboErikb214efb2014-07-24 13:20:30 -0700751 private PendingIntent mLastMediaButtonReceiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800752 private ComponentName mRestoredMediaButtonReceiver;
Jaewan Kima7dce192017-02-16 17:10:54 +0900753 private int mRestoredMediaButtonReceiverUserId;
RoboErik4646d282014-05-13 10:13:04 -0700754
Jaewan Kim50269362016-12-23 11:22:02 +0900755 private IOnVolumeKeyLongPressListener mOnVolumeKeyLongPressListener;
756 private int mOnVolumeKeyLongPressListenerUid;
757 private KeyEvent mInitialDownVolumeKeyEvent;
758 private int mInitialDownVolumeStream;
759 private boolean mInitialDownMusicOnly;
760
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800761 private IOnMediaKeyListener mOnMediaKeyListener;
762 private int mOnMediaKeyListenerUid;
Jaewan Kima7dce192017-02-16 17:10:54 +0900763 private ICallback mCallback;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800764
Jaewan Kima7dce192017-02-16 17:10:54 +0900765 public FullUserRecord(int fullUserId) {
766 mFullUserId = fullUserId;
Sungsoo Lim875e6972017-11-03 02:22:35 +0000767 mPriorityStack = new MediaSessionStack(mAudioPlayerStateMonitor, this);
Jaewan Kima7dce192017-02-16 17:10:54 +0900768 // Restore the remembered media button receiver before the boot.
769 String mediaButtonReceiver = Settings.Secure.getStringForUser(mContentResolver,
770 Settings.System.MEDIA_BUTTON_RECEIVER, mFullUserId);
771 if (mediaButtonReceiver == null) {
772 return;
773 }
774 String[] tokens = mediaButtonReceiver.split(COMPONENT_NAME_USER_ID_DELIM);
775 if (tokens == null || tokens.length != 2) {
776 return;
777 }
778 mRestoredMediaButtonReceiver = ComponentName.unflattenFromString(tokens[0]);
779 mRestoredMediaButtonReceiverUserId = Integer.parseInt(tokens[1]);
RoboErik4646d282014-05-13 10:13:04 -0700780 }
781
Jaewan Kima7dce192017-02-16 17:10:54 +0900782 public void destroySessionsForUserLocked(int userId) {
Jaewan Kim92dea332017-02-02 11:52:08 +0900783 List<MediaSessionRecord> sessions = mPriorityStack.getPriorityList(false, userId);
Jaewan Kima7dce192017-02-16 17:10:54 +0900784 for (MediaSessionRecord session : sessions) {
RoboErik4646d282014-05-13 10:13:04 -0700785 MediaSessionService.this.destroySessionLocked(session);
RoboErik4646d282014-05-13 10:13:04 -0700786 }
787 }
788
RoboErik4646d282014-05-13 10:13:04 -0700789 public void dumpLocked(PrintWriter pw, String prefix) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900790 pw.print(prefix + "Record for full_user=" + mFullUserId);
791 // Dump managed profile user ids associated with this user.
792 int size = mFullUserIds.size();
793 for (int i = 0; i < size; i++) {
794 if (mFullUserIds.keyAt(i) != mFullUserIds.valueAt(i)
795 && mFullUserIds.valueAt(i) == mFullUserId) {
796 pw.print(", profile_user=" + mFullUserIds.keyAt(i));
797 }
798 }
799 pw.println();
RoboErik4646d282014-05-13 10:13:04 -0700800 String indent = prefix + " ";
Jaewan Kima7dce192017-02-16 17:10:54 +0900801 pw.println(indent + "Volume key long-press listener: " + mOnVolumeKeyLongPressListener);
802 pw.println(indent + "Volume key long-press listener package: " +
Jaewan Kim50269362016-12-23 11:22:02 +0900803 getCallingPackageName(mOnVolumeKeyLongPressListenerUid));
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800804 pw.println(indent + "Media key listener: " + mOnMediaKeyListener);
805 pw.println(indent + "Media key listener package: " +
806 getCallingPackageName(mOnMediaKeyListenerUid));
Jaewan Kima7dce192017-02-16 17:10:54 +0900807 pw.println(indent + "Callback: " + mCallback);
808 pw.println(indent + "Last MediaButtonReceiver: " + mLastMediaButtonReceiver);
809 pw.println(indent + "Restored MediaButtonReceiver: " + mRestoredMediaButtonReceiver);
810 mPriorityStack.dump(pw, indent);
811 }
812
Jaewan Kim92dea332017-02-02 11:52:08 +0900813 @Override
814 public void onMediaButtonSessionChanged(MediaSessionRecord oldMediaButtonSession,
815 MediaSessionRecord newMediaButtonSession) {
816 if (DEBUG_KEY_EVENT) {
Jaewan Kim98e4aaf2017-05-12 17:06:47 +0900817 Log.d(TAG, "Media button session is changed to " + newMediaButtonSession);
Jaewan Kim92dea332017-02-02 11:52:08 +0900818 }
819 synchronized (mLock) {
820 if (oldMediaButtonSession != null) {
821 mHandler.postSessionsChanged(oldMediaButtonSession.getUserId());
822 }
823 if (newMediaButtonSession != null) {
824 rememberMediaButtonReceiverLocked(newMediaButtonSession);
825 mHandler.postSessionsChanged(newMediaButtonSession.getUserId());
826 }
827 pushAddressedPlayerChangedLocked();
828 }
829 }
830
831 // Remember media button receiver and keep it in the persistent storage.
832 public void rememberMediaButtonReceiverLocked(MediaSessionRecord record) {
Jaewan Kima7dce192017-02-16 17:10:54 +0900833 PendingIntent receiver = record.getMediaButtonReceiver();
Jaewan Kima7dce192017-02-16 17:10:54 +0900834 mLastMediaButtonReceiver = receiver;
Jaewan Kim92dea332017-02-02 11:52:08 +0900835 mRestoredMediaButtonReceiver = null;
836 String componentName = "";
837 if (receiver != null) {
838 ComponentName component = receiver.getIntent().getComponent();
839 if (component != null
840 && record.getPackageName().equals(component.getPackageName())) {
841 componentName = component.flattenToString();
842 }
RoboErik4646d282014-05-13 10:13:04 -0700843 }
Jaewan Kim92dea332017-02-02 11:52:08 +0900844 Settings.Secure.putStringForUser(mContentResolver,
845 Settings.System.MEDIA_BUTTON_RECEIVER,
846 componentName + COMPONENT_NAME_USER_ID_DELIM + record.getUserId(),
847 mFullUserId);
RoboErik4646d282014-05-13 10:13:04 -0700848 }
RoboErikc8f92d12015-01-05 16:48:07 -0800849
Jaewan Kima7dce192017-02-16 17:10:54 +0900850 private void pushAddressedPlayerChangedLocked() {
851 if (mCallback == null) {
852 return;
RoboErikc8f92d12015-01-05 16:48:07 -0800853 }
Jaewan Kima7dce192017-02-16 17:10:54 +0900854 try {
855 MediaSessionRecord mediaButtonSession = getMediaButtonSessionLocked();
856 if (mediaButtonSession != null) {
857 mCallback.onAddressedPlayerChangedToMediaSession(
858 new MediaSession.Token(mediaButtonSession.getControllerBinder()));
859 } else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
860 mCallback.onAddressedPlayerChangedToMediaButtonReceiver(
861 mCurrentFullUserRecord.mLastMediaButtonReceiver
862 .getIntent().getComponent());
863 } else if (mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
864 mCallback.onAddressedPlayerChangedToMediaButtonReceiver(
865 mCurrentFullUserRecord.mRestoredMediaButtonReceiver);
866 }
867 } catch (RemoteException e) {
868 Log.w(TAG, "Failed to pushAddressedPlayerChangedLocked", e);
869 }
870 }
871
872 private MediaSessionRecord getMediaButtonSessionLocked() {
Jaewan Kim92dea332017-02-02 11:52:08 +0900873 return isGlobalPriorityActiveLocked()
874 ? mGlobalPrioritySession : mPriorityStack.getMediaButtonSession();
RoboErikc8f92d12015-01-05 16:48:07 -0800875 }
RoboErik4646d282014-05-13 10:13:04 -0700876 }
877
RoboErik2e7a9162014-06-04 16:53:45 -0700878 final class SessionsListenerRecord implements IBinder.DeathRecipient {
879 private final IActiveSessionsListener mListener;
RoboErik7aef77b2014-08-08 15:56:54 -0700880 private final ComponentName mComponentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700881 private final int mUserId;
RoboErik7aef77b2014-08-08 15:56:54 -0700882 private final int mPid;
883 private final int mUid;
RoboErik2e7a9162014-06-04 16:53:45 -0700884
RoboErik7aef77b2014-08-08 15:56:54 -0700885 public SessionsListenerRecord(IActiveSessionsListener listener,
886 ComponentName componentName,
887 int userId, int pid, int uid) {
RoboErik2e7a9162014-06-04 16:53:45 -0700888 mListener = listener;
RoboErik7aef77b2014-08-08 15:56:54 -0700889 mComponentName = componentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700890 mUserId = userId;
RoboErik7aef77b2014-08-08 15:56:54 -0700891 mPid = pid;
892 mUid = uid;
RoboErik2e7a9162014-06-04 16:53:45 -0700893 }
894
895 @Override
896 public void binderDied() {
897 synchronized (mLock) {
898 mSessionsListeners.remove(this);
899 }
900 }
901 }
902
RoboErik7aef77b2014-08-08 15:56:54 -0700903 final class SettingsObserver extends ContentObserver {
904 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(
905 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
906
907 private SettingsObserver() {
908 super(null);
909 }
910
911 private void observe() {
912 mContentResolver.registerContentObserver(mSecureSettingsUri,
913 false, this, UserHandle.USER_ALL);
914 }
915
916 @Override
917 public void onChange(boolean selfChange, Uri uri) {
918 updateActiveSessionListeners();
919 }
920 }
921
RoboErik07c70772014-03-20 13:33:52 -0700922 class SessionManagerImpl extends ISessionManager.Stub {
RoboErik8a2cfc32014-05-16 11:19:38 -0700923 private static final String EXTRA_WAKELOCK_ACQUIRED =
924 "android.media.AudioService.WAKELOCK_ACQUIRED";
925 private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; // magic number
926
RoboErik9a9d0b52014-05-20 14:53:39 -0700927 private boolean mVoiceButtonDown = false;
928 private boolean mVoiceButtonHandled = false;
929
RoboErik07c70772014-03-20 13:33:52 -0700930 @Override
RoboErika5b02322014-05-07 17:05:49 -0700931 public ISession createSession(String packageName, ISessionCallback cb, String tag,
932 int userId) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800933 final int pid = Binder.getCallingPid();
934 final int uid = Binder.getCallingUid();
935 final long token = Binder.clearCallingIdentity();
936 try {
937 enforcePackageName(packageName, uid);
RoboErika5b02322014-05-07 17:05:49 -0700938 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
939 false /* allowAll */, true /* requireFull */, "createSession", packageName);
RoboErik01fe6612014-02-13 14:19:04 -0800940 if (cb == null) {
941 throw new IllegalArgumentException("Controller callback cannot be null");
942 }
RoboErika5b02322014-05-07 17:05:49 -0700943 return createSessionInternal(pid, uid, resolvedUserId, packageName, cb, tag)
944 .getSessionBinder();
RoboErike7880d82014-04-30 12:48:25 -0700945 } finally {
946 Binder.restoreCallingIdentity(token);
947 }
948 }
949
950 @Override
RoboErika5b02322014-05-07 17:05:49 -0700951 public List<IBinder> getSessions(ComponentName componentName, int userId) {
RoboErike7880d82014-04-30 12:48:25 -0700952 final int pid = Binder.getCallingPid();
953 final int uid = Binder.getCallingUid();
954 final long token = Binder.clearCallingIdentity();
955
956 try {
RoboErik2e7a9162014-06-04 16:53:45 -0700957 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
RoboErike7880d82014-04-30 12:48:25 -0700958 ArrayList<IBinder> binders = new ArrayList<IBinder>();
959 synchronized (mLock) {
Jaewan Kim101b4d52017-05-18 13:23:11 +0900960 List<MediaSessionRecord> records = getActiveSessionsLocked(resolvedUserId);
961 for (MediaSessionRecord record : records) {
962 binders.add(record.getControllerBinder().asBinder());
RoboErike7880d82014-04-30 12:48:25 -0700963 }
964 }
965 return binders;
RoboErik01fe6612014-02-13 14:19:04 -0800966 } finally {
967 Binder.restoreCallingIdentity(token);
968 }
969 }
RoboErika278ea72014-04-24 14:49:01 -0700970
RoboErik2e7a9162014-06-04 16:53:45 -0700971 @Override
972 public void addSessionsListener(IActiveSessionsListener listener,
973 ComponentName componentName, int userId) throws RemoteException {
974 final int pid = Binder.getCallingPid();
975 final int uid = Binder.getCallingUid();
976 final long token = Binder.clearCallingIdentity();
977
978 try {
979 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
980 synchronized (mLock) {
981 int index = findIndexOfSessionsListenerLocked(listener);
982 if (index != -1) {
983 Log.w(TAG, "ActiveSessionsListener is already added, ignoring");
984 return;
985 }
986 SessionsListenerRecord record = new SessionsListenerRecord(listener,
RoboErik7aef77b2014-08-08 15:56:54 -0700987 componentName, resolvedUserId, pid, uid);
RoboErik2e7a9162014-06-04 16:53:45 -0700988 try {
989 listener.asBinder().linkToDeath(record, 0);
990 } catch (RemoteException e) {
991 Log.e(TAG, "ActiveSessionsListener is dead, ignoring it", e);
992 return;
993 }
994 mSessionsListeners.add(record);
995 }
996 } finally {
997 Binder.restoreCallingIdentity(token);
998 }
999 }
1000
1001 @Override
1002 public void removeSessionsListener(IActiveSessionsListener listener)
1003 throws RemoteException {
1004 synchronized (mLock) {
1005 int index = findIndexOfSessionsListenerLocked(listener);
1006 if (index != -1) {
1007 SessionsListenerRecord record = mSessionsListeners.remove(index);
1008 try {
1009 record.mListener.asBinder().unlinkToDeath(record, 0);
1010 } catch (Exception e) {
1011 // ignore exceptions, the record is being removed
1012 }
1013 }
1014 }
1015 }
1016
RoboErik8a2cfc32014-05-16 11:19:38 -07001017 /**
1018 * Handles the dispatching of the media button events to one of the
1019 * registered listeners, or if there was none, broadcast an
1020 * ACTION_MEDIA_BUTTON intent to the rest of the system.
1021 *
1022 * @param keyEvent a non-null KeyEvent whose key code is one of the
1023 * supported media buttons
1024 * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held
1025 * while this key event is dispatched.
1026 */
1027 @Override
1028 public void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
1029 if (keyEvent == null || !KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
1030 Log.w(TAG, "Attempted to dispatch null or non-media key event.");
1031 return;
1032 }
Jeff Brown38d3feb2015-03-19 18:26:30 -07001033
RoboErik8a2cfc32014-05-16 11:19:38 -07001034 final int pid = Binder.getCallingPid();
1035 final int uid = Binder.getCallingUid();
1036 final long token = Binder.clearCallingIdentity();
RoboErik8a2cfc32014-05-16 11:19:38 -07001037 try {
Jeff Brown221a8272015-03-23 13:53:09 -07001038 if (DEBUG) {
1039 Log.d(TAG, "dispatchMediaKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
1040 + keyEvent);
1041 }
Jeff Brown38d3feb2015-03-19 18:26:30 -07001042 if (!isUserSetupComplete()) {
1043 // Global media key handling can have the side-effect of starting new
1044 // activities which is undesirable while setup is in progress.
1045 Slog.i(TAG, "Not dispatching media key event because user "
1046 + "setup is in progress.");
1047 return;
1048 }
1049
RoboErik8a2cfc32014-05-16 11:19:38 -07001050 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001051 boolean isGlobalPriorityActive = isGlobalPriorityActiveLocked();
Jaewan Kim51255012017-02-24 16:19:14 +09001052 if (isGlobalPriorityActive && uid != Process.SYSTEM_UID) {
1053 // Prevent dispatching key event through reflection while the global
1054 // priority session is active.
1055 Slog.i(TAG, "Only the system can dispatch media key event "
1056 + "to the global priority session.");
1057 return;
1058 }
Jaewan Kim98003d32017-02-24 18:33:04 +09001059 if (!isGlobalPriorityActive) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001060 if (mCurrentFullUserRecord.mOnMediaKeyListener != null) {
Jaewan Kim98003d32017-02-24 18:33:04 +09001061 if (DEBUG_KEY_EVENT) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001062 Log.d(TAG, "Send " + keyEvent + " to the media key listener");
Jaewan Kim98003d32017-02-24 18:33:04 +09001063 }
1064 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001065 mCurrentFullUserRecord.mOnMediaKeyListener.onMediaKey(keyEvent,
Jaewan Kim98003d32017-02-24 18:33:04 +09001066 new MediaKeyListenerResultReceiver(keyEvent, needWakeLock));
1067 return;
1068 } catch (RemoteException e) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001069 Log.w(TAG, "Failed to send " + keyEvent
1070 + " to the media key listener");
Jaewan Kim98003d32017-02-24 18:33:04 +09001071 }
1072 }
1073 }
Jaewan Kim51255012017-02-24 16:19:14 +09001074 if (!isGlobalPriorityActive && isVoiceKey(keyEvent.getKeyCode())) {
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001075 handleVoiceKeyEventLocked(keyEvent, needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -07001076 } else {
Jaewan Kim98003d32017-02-24 18:33:04 +09001077 dispatchMediaKeyEventLocked(keyEvent, needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -07001078 }
1079 }
1080 } finally {
1081 Binder.restoreCallingIdentity(token);
1082 }
1083 }
1084
RoboErika278ea72014-04-24 14:49:01 -07001085 @Override
Jaewan Kimbd16f452017-02-03 16:21:38 +09001086 public void setCallback(ICallback callback) {
1087 final int pid = Binder.getCallingPid();
1088 final int uid = Binder.getCallingUid();
1089 final long token = Binder.clearCallingIdentity();
1090 try {
Amith Yamasanie259ad22017-04-24 11:30:19 -07001091 if (!UserHandle.isSameApp(uid, Process.BLUETOOTH_UID)) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001092 throw new SecurityException("Only Bluetooth service processes can set"
1093 + " Callback");
1094 }
1095 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001096 int userId = UserHandle.getUserId(uid);
1097 FullUserRecord user = getFullUserRecordLocked(userId);
1098 if (user == null || user.mFullUserId != userId) {
1099 Log.w(TAG, "Only the full user can set the callback"
1100 + ", userId=" + userId);
1101 return;
1102 }
1103 user.mCallback = callback;
1104 Log.d(TAG, "The callback " + user.mCallback
Jaewan Kimbd16f452017-02-03 16:21:38 +09001105 + " is set by " + getCallingPackageName(uid));
Jaewan Kima7dce192017-02-16 17:10:54 +09001106 if (user.mCallback == null) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001107 return;
1108 }
1109 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001110 user.mCallback.asBinder().linkToDeath(
Jaewan Kimbd16f452017-02-03 16:21:38 +09001111 new IBinder.DeathRecipient() {
1112 @Override
1113 public void binderDied() {
1114 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001115 user.mCallback = null;
Jaewan Kimbd16f452017-02-03 16:21:38 +09001116 }
1117 }
1118 }, 0);
Jaewan Kima7dce192017-02-16 17:10:54 +09001119 user.pushAddressedPlayerChangedLocked();
Jaewan Kimbd16f452017-02-03 16:21:38 +09001120 } catch (RemoteException e) {
1121 Log.w(TAG, "Failed to set callback", e);
Jaewan Kima7dce192017-02-16 17:10:54 +09001122 user.mCallback = null;
Jaewan Kimbd16f452017-02-03 16:21:38 +09001123 }
1124 }
1125 } finally {
1126 Binder.restoreCallingIdentity(token);
1127 }
1128 }
1129
1130 @Override
Jaewan Kim50269362016-12-23 11:22:02 +09001131 public void setOnVolumeKeyLongPressListener(IOnVolumeKeyLongPressListener listener) {
1132 final int pid = Binder.getCallingPid();
1133 final int uid = Binder.getCallingUid();
1134 final long token = Binder.clearCallingIdentity();
1135 try {
1136 // Enforce SET_VOLUME_KEY_LONG_PRESS_LISTENER permission.
1137 if (getContext().checkPermission(
1138 android.Manifest.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER, pid, uid)
1139 != PackageManager.PERMISSION_GRANTED) {
1140 throw new SecurityException("Must hold the SET_VOLUME_KEY_LONG_PRESS_LISTENER" +
1141 " permission.");
1142 }
1143
1144 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001145 int userId = UserHandle.getUserId(uid);
1146 FullUserRecord user = getFullUserRecordLocked(userId);
1147 if (user == null || user.mFullUserId != userId) {
1148 Log.w(TAG, "Only the full user can set the volume key long-press listener"
1149 + ", userId=" + userId);
1150 return;
1151 }
Jaewan Kim50269362016-12-23 11:22:02 +09001152 if (user.mOnVolumeKeyLongPressListener != null &&
1153 user.mOnVolumeKeyLongPressListenerUid != uid) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001154 Log.w(TAG, "The volume key long-press listener cannot be reset"
1155 + " by another app , mOnVolumeKeyLongPressListener="
1156 + user.mOnVolumeKeyLongPressListenerUid
1157 + ", uid=" + uid);
Jaewan Kim50269362016-12-23 11:22:02 +09001158 return;
1159 }
1160
1161 user.mOnVolumeKeyLongPressListener = listener;
1162 user.mOnVolumeKeyLongPressListenerUid = uid;
1163
Jaewan Kima7dce192017-02-16 17:10:54 +09001164 Log.d(TAG, "The volume key long-press listener "
Jaewan Kim50269362016-12-23 11:22:02 +09001165 + listener + " is set by " + getCallingPackageName(uid));
1166
1167 if (user.mOnVolumeKeyLongPressListener != null) {
1168 try {
1169 user.mOnVolumeKeyLongPressListener.asBinder().linkToDeath(
1170 new IBinder.DeathRecipient() {
1171 @Override
1172 public void binderDied() {
1173 synchronized (mLock) {
1174 user.mOnVolumeKeyLongPressListener = null;
1175 }
1176 }
1177 }, 0);
1178 } catch (RemoteException e) {
1179 Log.w(TAG, "Failed to set death recipient "
1180 + user.mOnVolumeKeyLongPressListener);
1181 user.mOnVolumeKeyLongPressListener = null;
1182 }
1183 }
1184 }
1185 } finally {
1186 Binder.restoreCallingIdentity(token);
1187 }
1188 }
1189
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001190 @Override
1191 public void setOnMediaKeyListener(IOnMediaKeyListener listener) {
1192 final int pid = Binder.getCallingPid();
1193 final int uid = Binder.getCallingUid();
1194 final long token = Binder.clearCallingIdentity();
1195 try {
1196 // Enforce SET_MEDIA_KEY_LISTENER permission.
1197 if (getContext().checkPermission(
1198 android.Manifest.permission.SET_MEDIA_KEY_LISTENER, pid, uid)
1199 != PackageManager.PERMISSION_GRANTED) {
1200 throw new SecurityException("Must hold the SET_MEDIA_KEY_LISTENER" +
1201 " permission.");
1202 }
1203
1204 synchronized (mLock) {
1205 int userId = UserHandle.getUserId(uid);
Jaewan Kima7dce192017-02-16 17:10:54 +09001206 FullUserRecord user = getFullUserRecordLocked(userId);
1207 if (user == null || user.mFullUserId != userId) {
1208 Log.w(TAG, "Only the full user can set the media key listener"
1209 + ", userId=" + userId);
1210 return;
1211 }
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001212 if (user.mOnMediaKeyListener != null && user.mOnMediaKeyListenerUid != uid) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001213 Log.w(TAG, "The media key listener cannot be reset by another app. "
1214 + ", mOnMediaKeyListenerUid=" + user.mOnMediaKeyListenerUid
1215 + ", uid=" + uid);
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001216 return;
1217 }
1218
1219 user.mOnMediaKeyListener = listener;
1220 user.mOnMediaKeyListenerUid = uid;
1221
Jaewan Kima7dce192017-02-16 17:10:54 +09001222 Log.d(TAG, "The media key listener " + user.mOnMediaKeyListener
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001223 + " is set by " + getCallingPackageName(uid));
1224
1225 if (user.mOnMediaKeyListener != null) {
1226 try {
1227 user.mOnMediaKeyListener.asBinder().linkToDeath(
1228 new IBinder.DeathRecipient() {
1229 @Override
1230 public void binderDied() {
1231 synchronized (mLock) {
1232 user.mOnMediaKeyListener = null;
1233 }
1234 }
1235 }, 0);
1236 } catch (RemoteException e) {
1237 Log.w(TAG, "Failed to set death recipient " + user.mOnMediaKeyListener);
1238 user.mOnMediaKeyListener = null;
1239 }
1240 }
1241 }
1242 } finally {
1243 Binder.restoreCallingIdentity(token);
1244 }
1245 }
1246
Jaewan Kim50269362016-12-23 11:22:02 +09001247 /**
1248 * Handles the dispatching of the volume button events to one of the
1249 * registered listeners. If there's a volume key long-press listener and
1250 * there's no active global priority session, long-pressess will be sent to the
1251 * long-press listener instead of adjusting volume.
1252 *
1253 * @param keyEvent a non-null KeyEvent whose key code is one of the
1254 * {@link KeyEvent#KEYCODE_VOLUME_UP},
1255 * {@link KeyEvent#KEYCODE_VOLUME_DOWN},
1256 * or {@link KeyEvent#KEYCODE_VOLUME_MUTE}.
1257 * @param stream stream type to adjust volume.
1258 * @param musicOnly true if both UI nor haptic feedback aren't needed when adjust volume.
1259 */
1260 @Override
1261 public void dispatchVolumeKeyEvent(KeyEvent keyEvent, int stream, boolean musicOnly) {
1262 if (keyEvent == null ||
1263 (keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_UP
1264 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_DOWN
1265 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_MUTE)) {
1266 Log.w(TAG, "Attempted to dispatch null or non-volume key event.");
1267 return;
1268 }
1269
1270 final int pid = Binder.getCallingPid();
1271 final int uid = Binder.getCallingUid();
1272 final long token = Binder.clearCallingIdentity();
1273
Jaewan Kimb2781e72017-03-02 09:57:09 +09001274 if (DEBUG_KEY_EVENT) {
Jaewan Kim50269362016-12-23 11:22:02 +09001275 Log.d(TAG, "dispatchVolumeKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
1276 + keyEvent);
1277 }
1278
1279 try {
1280 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001281 if (isGlobalPriorityActiveLocked()
1282 || mCurrentFullUserRecord.mOnVolumeKeyLongPressListener == null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001283 dispatchVolumeKeyEventLocked(keyEvent, stream, musicOnly);
1284 } else {
1285 // TODO: Consider the case when both volume up and down keys are pressed
1286 // at the same time.
1287 if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
1288 if (keyEvent.getRepeatCount() == 0) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001289 // Keeps the copy of the KeyEvent because it can be reused.
Jaewan Kima7dce192017-02-16 17:10:54 +09001290 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent =
1291 KeyEvent.obtain(keyEvent);
1292 mCurrentFullUserRecord.mInitialDownVolumeStream = stream;
1293 mCurrentFullUserRecord.mInitialDownMusicOnly = musicOnly;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001294 mHandler.sendMessageDelayed(
1295 mHandler.obtainMessage(
Jaewan Kima7dce192017-02-16 17:10:54 +09001296 MessageHandler.MSG_VOLUME_INITIAL_DOWN,
1297 mCurrentFullUserRecord.mFullUserId, 0),
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001298 mLongPressTimeout);
Jaewan Kim50269362016-12-23 11:22:02 +09001299 }
1300 if (keyEvent.getRepeatCount() > 0 || keyEvent.isLongPress()) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001301 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kima7dce192017-02-16 17:10:54 +09001302 if (mCurrentFullUserRecord.mInitialDownVolumeKeyEvent != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001303 dispatchVolumeKeyLongPressLocked(
Jaewan Kima7dce192017-02-16 17:10:54 +09001304 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent);
Jaewan Kim50269362016-12-23 11:22:02 +09001305 // Mark that the key is already handled.
Jaewan Kima7dce192017-02-16 17:10:54 +09001306 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent = null;
Jaewan Kim50269362016-12-23 11:22:02 +09001307 }
1308 dispatchVolumeKeyLongPressLocked(keyEvent);
1309 }
1310 } else { // if up
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001311 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kima7dce192017-02-16 17:10:54 +09001312 if (mCurrentFullUserRecord.mInitialDownVolumeKeyEvent != null
1313 && mCurrentFullUserRecord.mInitialDownVolumeKeyEvent
1314 .getDownTime() == keyEvent.getDownTime()) {
Jaewan Kim50269362016-12-23 11:22:02 +09001315 // Short-press. Should change volume.
1316 dispatchVolumeKeyEventLocked(
Jaewan Kima7dce192017-02-16 17:10:54 +09001317 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent,
1318 mCurrentFullUserRecord.mInitialDownVolumeStream,
1319 mCurrentFullUserRecord.mInitialDownMusicOnly);
Jaewan Kim50269362016-12-23 11:22:02 +09001320 dispatchVolumeKeyEventLocked(keyEvent, stream, musicOnly);
1321 } else {
1322 dispatchVolumeKeyLongPressLocked(keyEvent);
1323 }
1324 }
1325 }
1326 }
1327 } finally {
1328 Binder.restoreCallingIdentity(token);
1329 }
1330 }
1331
Jaewan Kim50269362016-12-23 11:22:02 +09001332 private void dispatchVolumeKeyEventLocked(
1333 KeyEvent keyEvent, int stream, boolean musicOnly) {
1334 boolean down = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
1335 boolean up = keyEvent.getAction() == KeyEvent.ACTION_UP;
1336 int direction = 0;
1337 boolean isMute = false;
1338 switch (keyEvent.getKeyCode()) {
1339 case KeyEvent.KEYCODE_VOLUME_UP:
1340 direction = AudioManager.ADJUST_RAISE;
1341 break;
1342 case KeyEvent.KEYCODE_VOLUME_DOWN:
1343 direction = AudioManager.ADJUST_LOWER;
1344 break;
1345 case KeyEvent.KEYCODE_VOLUME_MUTE:
1346 isMute = true;
1347 break;
1348 }
1349 if (down || up) {
1350 int flags = AudioManager.FLAG_FROM_KEY;
1351 if (musicOnly) {
1352 // This flag is used when the screen is off to only affect active media.
1353 flags |= AudioManager.FLAG_ACTIVE_MEDIA_ONLY;
1354 } else {
1355 // These flags are consistent with the home screen
1356 if (up) {
1357 flags |= AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_VIBRATE;
1358 } else {
1359 flags |= AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_VIBRATE;
1360 }
1361 }
1362 if (direction != 0) {
1363 // If this is action up we want to send a beep for non-music events
1364 if (up) {
1365 direction = 0;
1366 }
1367 dispatchAdjustVolumeLocked(stream, direction, flags);
1368 } else if (isMute) {
1369 if (down && keyEvent.getRepeatCount() == 0) {
1370 dispatchAdjustVolumeLocked(stream, AudioManager.ADJUST_TOGGLE_MUTE, flags);
1371 }
1372 }
1373 }
1374 }
1375
1376 @Override
RoboErik7c82ced2014-12-04 17:39:08 -08001377 public void dispatchAdjustVolume(int suggestedStream, int delta, int flags) {
RoboErikb69ffd42014-05-30 14:57:59 -07001378 final long token = Binder.clearCallingIdentity();
1379 try {
1380 synchronized (mLock) {
Jaewan Kim50269362016-12-23 11:22:02 +09001381 dispatchAdjustVolumeLocked(suggestedStream, delta, flags);
RoboErikb69ffd42014-05-30 14:57:59 -07001382 }
1383 } finally {
1384 Binder.restoreCallingIdentity(token);
1385 }
1386 }
1387
1388 @Override
RoboErik19c95182014-06-23 15:38:48 -07001389 public void setRemoteVolumeController(IRemoteVolumeController rvc) {
1390 final int pid = Binder.getCallingPid();
1391 final int uid = Binder.getCallingUid();
1392 final long token = Binder.clearCallingIdentity();
1393 try {
John Spurlockeb69e242015-02-17 17:15:04 -05001394 enforceSystemUiPermission("listen for volume changes", pid, uid);
RoboErik19c95182014-06-23 15:38:48 -07001395 mRvc = rvc;
1396 } finally {
1397 Binder.restoreCallingIdentity(token);
1398 }
1399 }
1400
1401 @Override
RoboErikde9ba392014-09-26 12:51:01 -07001402 public boolean isGlobalPriorityActive() {
Jaewan Kim51255012017-02-24 16:19:14 +09001403 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001404 return isGlobalPriorityActiveLocked();
Jaewan Kim51255012017-02-24 16:19:14 +09001405 }
RoboErikde9ba392014-09-26 12:51:01 -07001406 }
1407
1408 @Override
RoboErika278ea72014-04-24 14:49:01 -07001409 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001410 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
RoboErika278ea72014-04-24 14:49:01 -07001411
1412 pw.println("MEDIA SESSION SERVICE (dumpsys media_session)");
1413 pw.println();
1414
1415 synchronized (mLock) {
RoboErika08adb242014-11-21 18:28:18 -08001416 pw.println(mSessionsListeners.size() + " sessions listeners.");
Jaewan Kima7dce192017-02-16 17:10:54 +09001417 pw.println("Global priority session is " + mGlobalPrioritySession);
Jaewan Kim101b4d52017-05-18 13:23:11 +09001418 if (mGlobalPrioritySession != null) {
1419 mGlobalPrioritySession.dump(pw, " ");
1420 }
RoboErik4646d282014-05-13 10:13:04 -07001421 pw.println("User Records:");
Jaewan Kime0ca3f32017-02-16 15:52:39 +09001422 int count = mUserRecords.size();
RoboErika278ea72014-04-24 14:49:01 -07001423 for (int i = 0; i < count; i++) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001424 mUserRecords.valueAt(i).dumpLocked(pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001425 }
Sungsoo Lim875e6972017-11-03 02:22:35 +00001426 mAudioPlayerStateMonitor.dump(getContext(), pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001427 }
1428 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001429
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001430 @Override
Jaewan Kimf7a77062018-01-27 01:34:24 +09001431 public boolean onSessionCreated(Bundle sessionToken) {
1432 final int uid = Binder.getCallingUid();
1433 final int pid = Binder.getCallingPid();
1434 final SessionToken2 token = SessionToken2.fromBundle(getContext(), sessionToken);
1435 if (token == null || token.getUid() != uid) {
1436 Log.w(TAG, "onSessionCreated failed, expected caller uid=" + token.getUid()
1437 + " but from uid=" + uid);
1438 }
1439 if (DEBUG) {
1440 Log.d(TAG, "onSessionCreated " + token);
1441 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001442 synchronized (mLock) {
Jaewan Kimf7a77062018-01-27 01:34:24 +09001443 MediaSession2Record record = getSessionRecordLocked(
1444 uid, token.getPackageName(), token.getId());
1445 if (record != null) {
1446 return record.onSessionCreated(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001447 } else {
Jaewan Kimf7a77062018-01-27 01:34:24 +09001448 record = new MediaSession2Record(
1449 getContext(), token, mSessionDestroyedListener);
1450 mSessions.add(record);
1451 return record.onSessionCreated(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001452 }
1453 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001454 }
1455
1456 @Override
1457 public void onSessionDestroyed(Bundle sessionToken) {
1458 final int uid = Binder.getCallingUid();
1459 final int pid = Binder.getCallingPid();
1460 final SessionToken2 token = SessionToken2.fromBundle(getContext(), sessionToken);
1461 if (token == null || token.getUid() != uid) {
1462 Log.w(TAG, "onSessionDestroyed failed, expected caller uid=" + token.getUid()
1463 + " but from uid=" + uid);
1464 }
1465 if (DEBUG) {
1466 Log.d(TAG, "onSessionDestroyed " + token);
1467 }
1468 synchronized (mLock) {
1469 MediaSession2Record record = getSessionRecordLocked(
1470 uid, token.getPackageName(), token.getId());
1471 if (record != null) {
1472 record.onSessionDestroyed();
1473 } else {
1474 if (DEBUG) {
1475 Log.d(TAG, "Cannot find a session record to destroy. uid=" + uid
1476 + ", pkg=" + token.getPackageName() + ", id=" + token.getId());
1477 }
1478 }
1479 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001480 }
1481
1482 // TODO(jaewan): Protect this API with permission
1483 // TODO(jaewan): Add listeners for change in operations..
1484 @Override
1485 public List<Bundle> getSessionTokens(boolean activeSessionOnly,
1486 boolean sessionServiceOnly) throws RemoteException {
1487 List<Bundle> tokens = new ArrayList<>();
1488 synchronized (mLock) {
1489 for (int i = 0; i < mSessions.size(); i++) {
1490 MediaSession2Record record = mSessions.get(i);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001491 boolean isSessionService = (record.getToken().getType() != TYPE_SESSION);
1492 boolean isActive = record.getController() != null;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001493 if ((!activeSessionOnly && isSessionService)
1494 || (!sessionServiceOnly && isActive)) {
Jaewan Kim04de5de2018-01-25 02:24:03 +09001495 SessionToken2 token = record.getToken();
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001496 if (token != null) {
1497 tokens.add(token.toBundle());
1498 } else {
1499 Log.wtf(TAG, "Null token for record=" + record);
1500 }
1501 }
1502 }
1503 }
1504 return tokens;
1505 }
1506
RoboErik2e7a9162014-06-04 16:53:45 -07001507 private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
1508 final int uid) {
1509 String packageName = null;
1510 if (componentName != null) {
1511 // If they gave us a component name verify they own the
1512 // package
1513 packageName = componentName.getPackageName();
1514 enforcePackageName(packageName, uid);
1515 }
1516 // Check that they can make calls on behalf of the user and
1517 // get the final user id
1518 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
1519 true /* allowAll */, true /* requireFull */, "getSessions", packageName);
1520 // Check if they have the permissions or their component is
1521 // enabled for the user they're calling from.
1522 enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
1523 return resolvedUserId;
1524 }
1525
Jaewan Kim50269362016-12-23 11:22:02 +09001526 private void dispatchAdjustVolumeLocked(int suggestedStream, int direction, int flags) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001527 MediaSessionRecord session = isGlobalPriorityActiveLocked() ? mGlobalPrioritySession
1528 : mCurrentFullUserRecord.mPriorityStack.getDefaultVolumeSession();
Jaewan Kim50269362016-12-23 11:22:02 +09001529
RoboErik9c785402014-11-11 16:52:26 -08001530 boolean preferSuggestedStream = false;
1531 if (isValidLocalStreamType(suggestedStream)
1532 && AudioSystem.isStreamActive(suggestedStream, 0)) {
1533 preferSuggestedStream = true;
1534 }
Jaewan Kimb2781e72017-03-02 09:57:09 +09001535 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001536 Log.d(TAG, "Adjusting " + session + " by " + direction + ". flags="
1537 + flags + ", suggestedStream=" + suggestedStream
1538 + ", preferSuggestedStream=" + preferSuggestedStream);
1539 }
RoboErik9c785402014-11-11 16:52:26 -08001540 if (session == null || preferSuggestedStream) {
RoboErik94c716e2014-09-14 13:54:31 -07001541 if ((flags & AudioManager.FLAG_ACTIVE_MEDIA_ONLY) != 0
1542 && !AudioSystem.isStreamActive(AudioManager.STREAM_MUSIC, 0)) {
RoboErik3c45c292014-07-08 16:47:31 -07001543 if (DEBUG) {
1544 Log.d(TAG, "No active session to adjust, skipping media only volume event");
RoboErik3c45c292014-07-08 16:47:31 -07001545 }
RoboErikb7c014c2014-07-22 15:58:22 -07001546 return;
RoboErik3c45c292014-07-08 16:47:31 -07001547 }
Shibin George19e84042016-06-14 20:42:13 +05301548
1549 // Execute mAudioService.adjustSuggestedStreamVolume() on
1550 // handler thread of MediaSessionService.
1551 // This will release the MediaSessionService.mLock sooner and avoid
1552 // a potential deadlock between MediaSessionService.mLock and
1553 // ActivityManagerService lock.
1554 mHandler.post(new Runnable() {
1555 @Override
1556 public void run() {
1557 try {
1558 String packageName = getContext().getOpPackageName();
1559 mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
1560 flags, packageName, TAG);
1561 } catch (RemoteException e) {
1562 Log.e(TAG, "Error adjusting default volume.", e);
Hyundo Moon739d6c22017-09-18 17:01:48 +09001563 } catch (IllegalArgumentException e) {
1564 Log.e(TAG, "Cannot adjust volume: direction=" + direction
1565 + ", suggestedStream=" + suggestedStream + ", flags=" + flags,
1566 e);
Shibin George19e84042016-06-14 20:42:13 +05301567 }
1568 }
1569 });
RoboErikb69ffd42014-05-30 14:57:59 -07001570 } else {
RoboErik0dac35a2014-08-12 15:48:49 -07001571 session.adjustVolume(direction, flags, getContext().getPackageName(),
Jaewan Kim8f729082016-06-21 12:36:26 +09001572 Process.SYSTEM_UID, true);
RoboErikb69ffd42014-05-30 14:57:59 -07001573 }
1574 }
1575
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001576 private void handleVoiceKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock) {
RoboErik9a9d0b52014-05-20 14:53:39 -07001577 int action = keyEvent.getAction();
1578 boolean isLongPress = (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0;
1579 if (action == KeyEvent.ACTION_DOWN) {
1580 if (keyEvent.getRepeatCount() == 0) {
1581 mVoiceButtonDown = true;
1582 mVoiceButtonHandled = false;
1583 } else if (mVoiceButtonDown && !mVoiceButtonHandled && isLongPress) {
1584 mVoiceButtonHandled = true;
1585 startVoiceInput(needWakeLock);
1586 }
1587 } else if (action == KeyEvent.ACTION_UP) {
1588 if (mVoiceButtonDown) {
1589 mVoiceButtonDown = false;
1590 if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
1591 // Resend the down then send this event through
1592 KeyEvent downEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_DOWN);
Jaewan Kim98003d32017-02-24 18:33:04 +09001593 dispatchMediaKeyEventLocked(downEvent, needWakeLock);
1594 dispatchMediaKeyEventLocked(keyEvent, needWakeLock);
RoboErik9a9d0b52014-05-20 14:53:39 -07001595 }
1596 }
1597 }
1598 }
1599
Jaewan Kim98003d32017-02-24 18:33:04 +09001600 private void dispatchMediaKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001601 MediaSessionRecord session = mCurrentFullUserRecord.getMediaButtonSessionLocked();
RoboErik9a9d0b52014-05-20 14:53:39 -07001602 if (session != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001603 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001604 Log.d(TAG, "Sending " + keyEvent + " to " + session);
RoboErik9a9d0b52014-05-20 14:53:39 -07001605 }
1606 if (needWakeLock) {
1607 mKeyEventReceiver.aquireWakeLockLocked();
1608 }
Jaewan Kim50269362016-12-23 11:22:02 +09001609 // If we don't need a wakelock use -1 as the id so we won't release it later.
RoboErik9a9d0b52014-05-20 14:53:39 -07001610 session.sendMediaButton(keyEvent,
1611 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
Jaewan Kim8f729082016-06-21 12:36:26 +09001612 mKeyEventReceiver, Process.SYSTEM_UID,
Donghyun Cho1ea56832016-02-23 16:30:07 +09001613 getContext().getPackageName());
Jaewan Kima7dce192017-02-16 17:10:54 +09001614 if (mCurrentFullUserRecord.mCallback != null) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001615 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001616 mCurrentFullUserRecord.mCallback.onMediaKeyEventDispatchedToMediaSession(
1617 keyEvent,
Jaewan Kimbd16f452017-02-03 16:21:38 +09001618 new MediaSession.Token(session.getControllerBinder()));
1619 } catch (RemoteException e) {
1620 Log.w(TAG, "Failed to send callback", e);
1621 }
1622 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001623 } else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null
1624 || mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
1625 if (needWakeLock) {
1626 mKeyEventReceiver.aquireWakeLockLocked();
1627 }
1628 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
1629 mediaButtonIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1630 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
1631 try {
1632 if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
1633 PendingIntent receiver = mCurrentFullUserRecord.mLastMediaButtonReceiver;
1634 if (DEBUG_KEY_EVENT) {
1635 Log.d(TAG, "Sending " + keyEvent
Jaewan Kim92dea332017-02-02 11:52:08 +09001636 + " to the last known PendingIntent " + receiver);
Jaewan Kima7dce192017-02-16 17:10:54 +09001637 }
1638 receiver.send(getContext(),
1639 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
1640 mediaButtonIntent, mKeyEventReceiver, mHandler);
1641 if (mCurrentFullUserRecord.mCallback != null) {
1642 ComponentName componentName = mCurrentFullUserRecord
1643 .mLastMediaButtonReceiver.getIntent().getComponent();
1644 if (componentName != null) {
1645 mCurrentFullUserRecord.mCallback
1646 .onMediaKeyEventDispatchedToMediaButtonReceiver(
1647 keyEvent, componentName);
Jaewan Kimbd16f452017-02-03 16:21:38 +09001648 }
RoboErikc8f92d12015-01-05 16:48:07 -08001649 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001650 } else {
1651 ComponentName receiver =
1652 mCurrentFullUserRecord.mRestoredMediaButtonReceiver;
1653 if (DEBUG_KEY_EVENT) {
1654 Log.d(TAG, "Sending " + keyEvent + " to the restored intent "
1655 + receiver);
1656 }
1657 mediaButtonIntent.setComponent(receiver);
1658 getContext().sendBroadcastAsUser(mediaButtonIntent,
Jaewan Kim92dea332017-02-02 11:52:08 +09001659 UserHandle.of(mCurrentFullUserRecord
1660 .mRestoredMediaButtonReceiverUserId));
Jaewan Kima7dce192017-02-16 17:10:54 +09001661 if (mCurrentFullUserRecord.mCallback != null) {
1662 mCurrentFullUserRecord.mCallback
1663 .onMediaKeyEventDispatchedToMediaButtonReceiver(
1664 keyEvent, receiver);
1665 }
RoboErikb214efb2014-07-24 13:20:30 -07001666 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001667 } catch (CanceledException e) {
1668 Log.i(TAG, "Error sending key event to media button receiver "
1669 + mCurrentFullUserRecord.mLastMediaButtonReceiver, e);
1670 } catch (RemoteException e) {
1671 Log.w(TAG, "Failed to send callback", e);
RoboErik9a9d0b52014-05-20 14:53:39 -07001672 }
RoboErik9a9d0b52014-05-20 14:53:39 -07001673 }
1674 }
1675
1676 private void startVoiceInput(boolean needWakeLock) {
1677 Intent voiceIntent = null;
1678 // select which type of search to launch:
1679 // - screen on and device unlocked: action is ACTION_WEB_SEARCH
1680 // - device locked or screen off: action is
1681 // ACTION_VOICE_SEARCH_HANDS_FREE
1682 // with EXTRA_SECURE set to true if the device is securely locked
1683 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1684 boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
1685 if (!isLocked && pm.isScreenOn()) {
1686 voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
1687 Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
1688 } else {
1689 voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
1690 voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
1691 isLocked && mKeyguardManager.isKeyguardSecure());
1692 Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
1693 }
1694 // start the search activity
1695 if (needWakeLock) {
1696 mMediaEventWakeLock.acquire();
1697 }
1698 try {
1699 if (voiceIntent != null) {
1700 voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1701 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Jaewan Kim8f729082016-06-21 12:36:26 +09001702 if (DEBUG) Log.d(TAG, "voiceIntent: " + voiceIntent);
RoboErik9a9d0b52014-05-20 14:53:39 -07001703 getContext().startActivityAsUser(voiceIntent, UserHandle.CURRENT);
1704 }
1705 } catch (ActivityNotFoundException e) {
1706 Log.w(TAG, "No activity for search: " + e);
1707 } finally {
1708 if (needWakeLock) {
1709 mMediaEventWakeLock.release();
1710 }
1711 }
1712 }
1713
1714 private boolean isVoiceKey(int keyCode) {
Jaewan Kimba18d8e2017-05-12 17:37:57 +09001715 return keyCode == KeyEvent.KEYCODE_HEADSETHOOK
Jaewan Kimfdb612e2017-07-01 09:23:41 +09001716 || (!mHasFeatureLeanback && keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
RoboErik9a9d0b52014-05-20 14:53:39 -07001717 }
1718
Jeff Brown38d3feb2015-03-19 18:26:30 -07001719 private boolean isUserSetupComplete() {
1720 return Settings.Secure.getIntForUser(getContext().getContentResolver(),
1721 Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1722 }
1723
RoboErik9c785402014-11-11 16:52:26 -08001724 // we only handle public stream types, which are 0-5
1725 private boolean isValidLocalStreamType(int streamType) {
1726 return streamType >= AudioManager.STREAM_VOICE_CALL
1727 && streamType <= AudioManager.STREAM_NOTIFICATION;
1728 }
1729
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001730 private class MediaKeyListenerResultReceiver extends ResultReceiver implements Runnable {
1731 private KeyEvent mKeyEvent;
1732 private boolean mNeedWakeLock;
1733 private boolean mHandled;
1734
1735 private MediaKeyListenerResultReceiver(KeyEvent keyEvent, boolean needWakeLock) {
1736 super(mHandler);
1737 mHandler.postDelayed(this, MEDIA_KEY_LISTENER_TIMEOUT);
1738 mKeyEvent = keyEvent;
1739 mNeedWakeLock = needWakeLock;
1740 }
1741
1742 @Override
1743 public void run() {
1744 Log.d(TAG, "The media key listener is timed-out for " + mKeyEvent);
1745 dispatchMediaKeyEvent();
1746 }
1747
1748 @Override
1749 protected void onReceiveResult(int resultCode, Bundle resultData) {
1750 if (resultCode == MediaSessionManager.RESULT_MEDIA_KEY_HANDLED) {
1751 mHandled = true;
1752 mHandler.removeCallbacks(this);
1753 return;
1754 }
1755 dispatchMediaKeyEvent();
1756 }
1757
1758 private void dispatchMediaKeyEvent() {
1759 if (mHandled) {
1760 return;
1761 }
1762 mHandled = true;
1763 mHandler.removeCallbacks(this);
1764 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001765 if (!isGlobalPriorityActiveLocked()
Jaewan Kim98003d32017-02-24 18:33:04 +09001766 && isVoiceKey(mKeyEvent.getKeyCode())) {
1767 handleVoiceKeyEventLocked(mKeyEvent, mNeedWakeLock);
1768 } else {
1769 dispatchMediaKeyEventLocked(mKeyEvent, mNeedWakeLock);
1770 }
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001771 }
1772 }
1773 }
1774
RoboErik418c10c2014-05-19 09:25:25 -07001775 private KeyEventWakeLockReceiver mKeyEventReceiver = new KeyEventWakeLockReceiver(mHandler);
1776
RoboErikb214efb2014-07-24 13:20:30 -07001777 class KeyEventWakeLockReceiver extends ResultReceiver implements Runnable,
1778 PendingIntent.OnFinished {
RoboErik418c10c2014-05-19 09:25:25 -07001779 private final Handler mHandler;
1780 private int mRefCount = 0;
1781 private int mLastTimeoutId = 0;
1782
1783 public KeyEventWakeLockReceiver(Handler handler) {
1784 super(handler);
1785 mHandler = handler;
1786 }
1787
1788 public void onTimeout() {
1789 synchronized (mLock) {
1790 if (mRefCount == 0) {
1791 // We've already released it, so just return
1792 return;
1793 }
1794 mLastTimeoutId++;
1795 mRefCount = 0;
1796 releaseWakeLockLocked();
1797 }
1798 }
1799
1800 public void aquireWakeLockLocked() {
1801 if (mRefCount == 0) {
1802 mMediaEventWakeLock.acquire();
1803 }
1804 mRefCount++;
1805 mHandler.removeCallbacks(this);
1806 mHandler.postDelayed(this, WAKELOCK_TIMEOUT);
1807
1808 }
1809
1810 @Override
1811 public void run() {
1812 onTimeout();
1813 }
1814
RoboErik8a2cfc32014-05-16 11:19:38 -07001815 @Override
1816 protected void onReceiveResult(int resultCode, Bundle resultData) {
RoboErik418c10c2014-05-19 09:25:25 -07001817 if (resultCode < mLastTimeoutId) {
1818 // Ignore results from calls that were before the last
1819 // timeout, just in case.
1820 return;
1821 } else {
1822 synchronized (mLock) {
1823 if (mRefCount > 0) {
1824 mRefCount--;
1825 if (mRefCount == 0) {
1826 releaseWakeLockLocked();
1827 }
1828 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001829 }
1830 }
1831 }
RoboErik418c10c2014-05-19 09:25:25 -07001832
1833 private void releaseWakeLockLocked() {
1834 mMediaEventWakeLock.release();
1835 mHandler.removeCallbacks(this);
1836 }
RoboErikb214efb2014-07-24 13:20:30 -07001837
1838 @Override
1839 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
1840 String resultData, Bundle resultExtras) {
1841 onReceiveResult(resultCode, null);
1842 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001843 };
1844
1845 BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
1846 @Override
1847 public void onReceive(Context context, Intent intent) {
1848 if (intent == null) {
1849 return;
1850 }
1851 Bundle extras = intent.getExtras();
1852 if (extras == null) {
1853 return;
1854 }
1855 synchronized (mLock) {
1856 if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)
1857 && mMediaEventWakeLock.isHeld()) {
1858 mMediaEventWakeLock.release();
1859 }
1860 }
1861 }
1862 };
RoboErik01fe6612014-02-13 14:19:04 -08001863 }
1864
RoboErik2e7a9162014-06-04 16:53:45 -07001865 final class MessageHandler extends Handler {
1866 private static final int MSG_SESSIONS_CHANGED = 1;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001867 private static final int MSG_VOLUME_INITIAL_DOWN = 2;
Jaewan Kim92dea332017-02-02 11:52:08 +09001868 private final SparseArray<Integer> mIntegerCache = new SparseArray<>();
RoboErik2e7a9162014-06-04 16:53:45 -07001869
1870 @Override
1871 public void handleMessage(Message msg) {
1872 switch (msg.what) {
1873 case MSG_SESSIONS_CHANGED:
Jaewan Kim92dea332017-02-02 11:52:08 +09001874 pushSessionsChanged((int) msg.obj);
RoboErik2e7a9162014-06-04 16:53:45 -07001875 break;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001876 case MSG_VOLUME_INITIAL_DOWN:
1877 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001878 FullUserRecord user = mUserRecords.get((int) msg.arg1);
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001879 if (user != null && user.mInitialDownVolumeKeyEvent != null) {
1880 dispatchVolumeKeyLongPressLocked(user.mInitialDownVolumeKeyEvent);
1881 // Mark that the key is already handled.
1882 user.mInitialDownVolumeKeyEvent = null;
1883 }
1884 }
1885 break;
RoboErik2e7a9162014-06-04 16:53:45 -07001886 }
1887 }
1888
Jaewan Kim92dea332017-02-02 11:52:08 +09001889 public void postSessionsChanged(int userId) {
1890 // Use object instead of the arguments when posting message to remove pending requests.
1891 Integer userIdInteger = mIntegerCache.get(userId);
1892 if (userIdInteger == null) {
1893 userIdInteger = Integer.valueOf(userId);
1894 mIntegerCache.put(userId, userIdInteger);
1895 }
1896 removeMessages(MSG_SESSIONS_CHANGED, userIdInteger);
1897 obtainMessage(MSG_SESSIONS_CHANGED, userIdInteger).sendToTarget();
RoboErik2e7a9162014-06-04 16:53:45 -07001898 }
1899 }
RoboErik01fe6612014-02-13 14:19:04 -08001900}