blob: 6fff3676ac8dd7576b8ae3f4d08f6189c34e93dd [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 *
Jaewan Kim77748b62018-05-03 19:43:33 +09001096 * @param packageName The caller package
1097 * @param asSystemService {@code true} if the event sent to the session as if it was come
1098 * from the system service instead of the app process. This helps sessions to
1099 * distinguish between the key injection by the app and key events from the
1100 * hardware devices. Should be used only when the volume key events aren't handled
1101 * by foreground activity. {@code false} otherwise to tell session about the real
1102 * caller.
RoboErik8a2cfc32014-05-16 11:19:38 -07001103 * @param keyEvent a non-null KeyEvent whose key code is one of the
1104 * supported media buttons
1105 * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held
1106 * while this key event is dispatched.
1107 */
1108 @Override
Jaewan Kim77748b62018-05-03 19:43:33 +09001109 public void dispatchMediaKeyEvent(String packageName, boolean asSystemService,
1110 KeyEvent keyEvent, boolean needWakeLock) {
RoboErik8a2cfc32014-05-16 11:19:38 -07001111 if (keyEvent == null || !KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
1112 Log.w(TAG, "Attempted to dispatch null or non-media key event.");
1113 return;
1114 }
Jeff Brown38d3feb2015-03-19 18:26:30 -07001115
RoboErik8a2cfc32014-05-16 11:19:38 -07001116 final int pid = Binder.getCallingPid();
1117 final int uid = Binder.getCallingUid();
1118 final long token = Binder.clearCallingIdentity();
RoboErik8a2cfc32014-05-16 11:19:38 -07001119 try {
Jeff Brown221a8272015-03-23 13:53:09 -07001120 if (DEBUG) {
Jaewan Kim77748b62018-05-03 19:43:33 +09001121 Log.d(TAG, "dispatchMediaKeyEvent, pkg=" + packageName + " pid=" + pid
1122 + ", uid=" + uid + ", asSystem=" + asSystemService + ", event="
Jeff Brown221a8272015-03-23 13:53:09 -07001123 + keyEvent);
1124 }
Jeff Brown38d3feb2015-03-19 18:26:30 -07001125 if (!isUserSetupComplete()) {
1126 // Global media key handling can have the side-effect of starting new
1127 // activities which is undesirable while setup is in progress.
1128 Slog.i(TAG, "Not dispatching media key event because user "
1129 + "setup is in progress.");
1130 return;
1131 }
1132
RoboErik8a2cfc32014-05-16 11:19:38 -07001133 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001134 boolean isGlobalPriorityActive = isGlobalPriorityActiveLocked();
Jaewan Kim51255012017-02-24 16:19:14 +09001135 if (isGlobalPriorityActive && uid != Process.SYSTEM_UID) {
1136 // Prevent dispatching key event through reflection while the global
1137 // priority session is active.
1138 Slog.i(TAG, "Only the system can dispatch media key event "
1139 + "to the global priority session.");
1140 return;
1141 }
Jaewan Kim98003d32017-02-24 18:33:04 +09001142 if (!isGlobalPriorityActive) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001143 if (mCurrentFullUserRecord.mOnMediaKeyListener != null) {
Jaewan Kim98003d32017-02-24 18:33:04 +09001144 if (DEBUG_KEY_EVENT) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001145 Log.d(TAG, "Send " + keyEvent + " to the media key listener");
Jaewan Kim98003d32017-02-24 18:33:04 +09001146 }
1147 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001148 mCurrentFullUserRecord.mOnMediaKeyListener.onMediaKey(keyEvent,
Jaewan Kim77748b62018-05-03 19:43:33 +09001149 new MediaKeyListenerResultReceiver(packageName, pid, uid,
1150 asSystemService, keyEvent, needWakeLock));
Jaewan Kim98003d32017-02-24 18:33:04 +09001151 return;
1152 } catch (RemoteException e) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001153 Log.w(TAG, "Failed to send " + keyEvent
1154 + " to the media key listener");
Jaewan Kim98003d32017-02-24 18:33:04 +09001155 }
1156 }
1157 }
Jaewan Kim51255012017-02-24 16:19:14 +09001158 if (!isGlobalPriorityActive && isVoiceKey(keyEvent.getKeyCode())) {
Jaewan Kim77748b62018-05-03 19:43:33 +09001159 handleVoiceKeyEventLocked(packageName, pid, uid, asSystemService, keyEvent,
1160 needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -07001161 } else {
Jaewan Kim77748b62018-05-03 19:43:33 +09001162 dispatchMediaKeyEventLocked(packageName, pid, uid, asSystemService,
1163 keyEvent, needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -07001164 }
1165 }
1166 } finally {
1167 Binder.restoreCallingIdentity(token);
1168 }
1169 }
1170
RoboErika278ea72014-04-24 14:49:01 -07001171 @Override
Jaewan Kimbd16f452017-02-03 16:21:38 +09001172 public void setCallback(ICallback callback) {
1173 final int pid = Binder.getCallingPid();
1174 final int uid = Binder.getCallingUid();
1175 final long token = Binder.clearCallingIdentity();
1176 try {
Amith Yamasanie259ad22017-04-24 11:30:19 -07001177 if (!UserHandle.isSameApp(uid, Process.BLUETOOTH_UID)) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001178 throw new SecurityException("Only Bluetooth service processes can set"
1179 + " Callback");
1180 }
1181 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001182 int userId = UserHandle.getUserId(uid);
1183 FullUserRecord user = getFullUserRecordLocked(userId);
1184 if (user == null || user.mFullUserId != userId) {
1185 Log.w(TAG, "Only the full user can set the callback"
1186 + ", userId=" + userId);
1187 return;
1188 }
1189 user.mCallback = callback;
1190 Log.d(TAG, "The callback " + user.mCallback
Jaewan Kimbd16f452017-02-03 16:21:38 +09001191 + " is set by " + getCallingPackageName(uid));
Jaewan Kima7dce192017-02-16 17:10:54 +09001192 if (user.mCallback == null) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001193 return;
1194 }
1195 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001196 user.mCallback.asBinder().linkToDeath(
Jaewan Kimbd16f452017-02-03 16:21:38 +09001197 new IBinder.DeathRecipient() {
1198 @Override
1199 public void binderDied() {
1200 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001201 user.mCallback = null;
Jaewan Kimbd16f452017-02-03 16:21:38 +09001202 }
1203 }
1204 }, 0);
Jaewan Kima7dce192017-02-16 17:10:54 +09001205 user.pushAddressedPlayerChangedLocked();
Jaewan Kimbd16f452017-02-03 16:21:38 +09001206 } catch (RemoteException e) {
1207 Log.w(TAG, "Failed to set callback", e);
Jaewan Kima7dce192017-02-16 17:10:54 +09001208 user.mCallback = null;
Jaewan Kimbd16f452017-02-03 16:21:38 +09001209 }
1210 }
1211 } finally {
1212 Binder.restoreCallingIdentity(token);
1213 }
1214 }
1215
1216 @Override
Jaewan Kim50269362016-12-23 11:22:02 +09001217 public void setOnVolumeKeyLongPressListener(IOnVolumeKeyLongPressListener listener) {
1218 final int pid = Binder.getCallingPid();
1219 final int uid = Binder.getCallingUid();
1220 final long token = Binder.clearCallingIdentity();
1221 try {
1222 // Enforce SET_VOLUME_KEY_LONG_PRESS_LISTENER permission.
1223 if (getContext().checkPermission(
1224 android.Manifest.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER, pid, uid)
1225 != PackageManager.PERMISSION_GRANTED) {
1226 throw new SecurityException("Must hold the SET_VOLUME_KEY_LONG_PRESS_LISTENER" +
1227 " permission.");
1228 }
1229
1230 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001231 int userId = UserHandle.getUserId(uid);
1232 FullUserRecord user = getFullUserRecordLocked(userId);
1233 if (user == null || user.mFullUserId != userId) {
1234 Log.w(TAG, "Only the full user can set the volume key long-press listener"
1235 + ", userId=" + userId);
1236 return;
1237 }
Jaewan Kim50269362016-12-23 11:22:02 +09001238 if (user.mOnVolumeKeyLongPressListener != null &&
1239 user.mOnVolumeKeyLongPressListenerUid != uid) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001240 Log.w(TAG, "The volume key long-press listener cannot be reset"
1241 + " by another app , mOnVolumeKeyLongPressListener="
1242 + user.mOnVolumeKeyLongPressListenerUid
1243 + ", uid=" + uid);
Jaewan Kim50269362016-12-23 11:22:02 +09001244 return;
1245 }
1246
1247 user.mOnVolumeKeyLongPressListener = listener;
1248 user.mOnVolumeKeyLongPressListenerUid = uid;
1249
Jaewan Kima7dce192017-02-16 17:10:54 +09001250 Log.d(TAG, "The volume key long-press listener "
Jaewan Kim50269362016-12-23 11:22:02 +09001251 + listener + " is set by " + getCallingPackageName(uid));
1252
1253 if (user.mOnVolumeKeyLongPressListener != null) {
1254 try {
1255 user.mOnVolumeKeyLongPressListener.asBinder().linkToDeath(
1256 new IBinder.DeathRecipient() {
1257 @Override
1258 public void binderDied() {
1259 synchronized (mLock) {
1260 user.mOnVolumeKeyLongPressListener = null;
1261 }
1262 }
1263 }, 0);
1264 } catch (RemoteException e) {
1265 Log.w(TAG, "Failed to set death recipient "
1266 + user.mOnVolumeKeyLongPressListener);
1267 user.mOnVolumeKeyLongPressListener = null;
1268 }
1269 }
1270 }
1271 } finally {
1272 Binder.restoreCallingIdentity(token);
1273 }
1274 }
1275
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001276 @Override
1277 public void setOnMediaKeyListener(IOnMediaKeyListener listener) {
1278 final int pid = Binder.getCallingPid();
1279 final int uid = Binder.getCallingUid();
1280 final long token = Binder.clearCallingIdentity();
1281 try {
1282 // Enforce SET_MEDIA_KEY_LISTENER permission.
1283 if (getContext().checkPermission(
1284 android.Manifest.permission.SET_MEDIA_KEY_LISTENER, pid, uid)
1285 != PackageManager.PERMISSION_GRANTED) {
1286 throw new SecurityException("Must hold the SET_MEDIA_KEY_LISTENER" +
1287 " permission.");
1288 }
1289
1290 synchronized (mLock) {
1291 int userId = UserHandle.getUserId(uid);
Jaewan Kima7dce192017-02-16 17:10:54 +09001292 FullUserRecord user = getFullUserRecordLocked(userId);
1293 if (user == null || user.mFullUserId != userId) {
1294 Log.w(TAG, "Only the full user can set the media key listener"
1295 + ", userId=" + userId);
1296 return;
1297 }
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001298 if (user.mOnMediaKeyListener != null && user.mOnMediaKeyListenerUid != uid) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001299 Log.w(TAG, "The media key listener cannot be reset by another app. "
1300 + ", mOnMediaKeyListenerUid=" + user.mOnMediaKeyListenerUid
1301 + ", uid=" + uid);
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001302 return;
1303 }
1304
1305 user.mOnMediaKeyListener = listener;
1306 user.mOnMediaKeyListenerUid = uid;
1307
Jaewan Kima7dce192017-02-16 17:10:54 +09001308 Log.d(TAG, "The media key listener " + user.mOnMediaKeyListener
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001309 + " is set by " + getCallingPackageName(uid));
1310
1311 if (user.mOnMediaKeyListener != null) {
1312 try {
1313 user.mOnMediaKeyListener.asBinder().linkToDeath(
1314 new IBinder.DeathRecipient() {
1315 @Override
1316 public void binderDied() {
1317 synchronized (mLock) {
1318 user.mOnMediaKeyListener = null;
1319 }
1320 }
1321 }, 0);
1322 } catch (RemoteException e) {
1323 Log.w(TAG, "Failed to set death recipient " + user.mOnMediaKeyListener);
1324 user.mOnMediaKeyListener = null;
1325 }
1326 }
1327 }
1328 } finally {
1329 Binder.restoreCallingIdentity(token);
1330 }
1331 }
1332
Jaewan Kim50269362016-12-23 11:22:02 +09001333 /**
1334 * Handles the dispatching of the volume button events to one of the
1335 * registered listeners. If there's a volume key long-press listener and
1336 * there's no active global priority session, long-pressess will be sent to the
1337 * long-press listener instead of adjusting volume.
1338 *
Jaewan Kim77748b62018-05-03 19:43:33 +09001339 * @param packageName The caller package.
1340 * @param asSystemService {@code true} if the event sent to the session as if it was come
1341 * from the system service instead of the app process. This helps sessions to
1342 * distinguish between the key injection by the app and key events from the
1343 * hardware devices. Should be used only when the volume key events aren't handled
1344 * by foreground activity. {@code false} otherwise to tell session about the real
1345 * caller.
Jaewan Kim50269362016-12-23 11:22:02 +09001346 * @param keyEvent a non-null KeyEvent whose key code is one of the
1347 * {@link KeyEvent#KEYCODE_VOLUME_UP},
1348 * {@link KeyEvent#KEYCODE_VOLUME_DOWN},
1349 * or {@link KeyEvent#KEYCODE_VOLUME_MUTE}.
1350 * @param stream stream type to adjust volume.
1351 * @param musicOnly true if both UI nor haptic feedback aren't needed when adjust volume.
1352 */
1353 @Override
Jaewan Kim77748b62018-05-03 19:43:33 +09001354 public void dispatchVolumeKeyEvent(String packageName, boolean asSystemService,
1355 KeyEvent keyEvent, int stream, boolean musicOnly) {
Jaewan Kim50269362016-12-23 11:22:02 +09001356 if (keyEvent == null ||
1357 (keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_UP
1358 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_DOWN
1359 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_MUTE)) {
1360 Log.w(TAG, "Attempted to dispatch null or non-volume key event.");
1361 return;
1362 }
1363
1364 final int pid = Binder.getCallingPid();
1365 final int uid = Binder.getCallingUid();
1366 final long token = Binder.clearCallingIdentity();
1367
Jaewan Kimb2781e72017-03-02 09:57:09 +09001368 if (DEBUG_KEY_EVENT) {
Jaewan Kim77748b62018-05-03 19:43:33 +09001369 Log.d(TAG, "dispatchVolumeKeyEvent, pkg=" + packageName + ", pid=" + pid + ", uid="
1370 + uid + ", asSystem=" + asSystemService + ", event=" + keyEvent);
Jaewan Kim50269362016-12-23 11:22:02 +09001371 }
1372
1373 try {
1374 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001375 if (isGlobalPriorityActiveLocked()
1376 || mCurrentFullUserRecord.mOnVolumeKeyLongPressListener == null) {
Jaewan Kim77748b62018-05-03 19:43:33 +09001377 dispatchVolumeKeyEventLocked(packageName, pid, uid, asSystemService,
1378 keyEvent, stream, musicOnly);
Jaewan Kim50269362016-12-23 11:22:02 +09001379 } else {
1380 // TODO: Consider the case when both volume up and down keys are pressed
1381 // at the same time.
1382 if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
1383 if (keyEvent.getRepeatCount() == 0) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001384 // Keeps the copy of the KeyEvent because it can be reused.
Jaewan Kima7dce192017-02-16 17:10:54 +09001385 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent =
1386 KeyEvent.obtain(keyEvent);
1387 mCurrentFullUserRecord.mInitialDownVolumeStream = stream;
1388 mCurrentFullUserRecord.mInitialDownMusicOnly = musicOnly;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001389 mHandler.sendMessageDelayed(
1390 mHandler.obtainMessage(
Jaewan Kima7dce192017-02-16 17:10:54 +09001391 MessageHandler.MSG_VOLUME_INITIAL_DOWN,
1392 mCurrentFullUserRecord.mFullUserId, 0),
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001393 mLongPressTimeout);
Jaewan Kim50269362016-12-23 11:22:02 +09001394 }
1395 if (keyEvent.getRepeatCount() > 0 || keyEvent.isLongPress()) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001396 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kima7dce192017-02-16 17:10:54 +09001397 if (mCurrentFullUserRecord.mInitialDownVolumeKeyEvent != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001398 dispatchVolumeKeyLongPressLocked(
Jaewan Kima7dce192017-02-16 17:10:54 +09001399 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent);
Jaewan Kim50269362016-12-23 11:22:02 +09001400 // Mark that the key is already handled.
Jaewan Kima7dce192017-02-16 17:10:54 +09001401 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent = null;
Jaewan Kim50269362016-12-23 11:22:02 +09001402 }
1403 dispatchVolumeKeyLongPressLocked(keyEvent);
1404 }
1405 } else { // if up
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001406 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kima7dce192017-02-16 17:10:54 +09001407 if (mCurrentFullUserRecord.mInitialDownVolumeKeyEvent != null
1408 && mCurrentFullUserRecord.mInitialDownVolumeKeyEvent
1409 .getDownTime() == keyEvent.getDownTime()) {
Jaewan Kim50269362016-12-23 11:22:02 +09001410 // Short-press. Should change volume.
Jaewan Kim77748b62018-05-03 19:43:33 +09001411 dispatchVolumeKeyEventLocked(packageName, pid, uid, asSystemService,
Jaewan Kima7dce192017-02-16 17:10:54 +09001412 mCurrentFullUserRecord.mInitialDownVolumeKeyEvent,
1413 mCurrentFullUserRecord.mInitialDownVolumeStream,
1414 mCurrentFullUserRecord.mInitialDownMusicOnly);
Jaewan Kim77748b62018-05-03 19:43:33 +09001415 dispatchVolumeKeyEventLocked(packageName, pid, uid, asSystemService,
1416 keyEvent, stream, musicOnly);
Jaewan Kim50269362016-12-23 11:22:02 +09001417 } else {
1418 dispatchVolumeKeyLongPressLocked(keyEvent);
1419 }
1420 }
1421 }
1422 }
1423 } finally {
1424 Binder.restoreCallingIdentity(token);
1425 }
1426 }
1427
Jaewan Kim77748b62018-05-03 19:43:33 +09001428 private void dispatchVolumeKeyEventLocked(String packageName, int pid, int uid,
1429 boolean asSystemService, KeyEvent keyEvent, int stream, boolean musicOnly) {
Jaewan Kim50269362016-12-23 11:22:02 +09001430 boolean down = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
1431 boolean up = keyEvent.getAction() == KeyEvent.ACTION_UP;
1432 int direction = 0;
1433 boolean isMute = false;
1434 switch (keyEvent.getKeyCode()) {
1435 case KeyEvent.KEYCODE_VOLUME_UP:
1436 direction = AudioManager.ADJUST_RAISE;
1437 break;
1438 case KeyEvent.KEYCODE_VOLUME_DOWN:
1439 direction = AudioManager.ADJUST_LOWER;
1440 break;
1441 case KeyEvent.KEYCODE_VOLUME_MUTE:
1442 isMute = true;
1443 break;
1444 }
1445 if (down || up) {
1446 int flags = AudioManager.FLAG_FROM_KEY;
1447 if (musicOnly) {
1448 // This flag is used when the screen is off to only affect active media.
1449 flags |= AudioManager.FLAG_ACTIVE_MEDIA_ONLY;
1450 } else {
1451 // These flags are consistent with the home screen
1452 if (up) {
1453 flags |= AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_VIBRATE;
1454 } else {
1455 flags |= AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_VIBRATE;
1456 }
1457 }
1458 if (direction != 0) {
1459 // If this is action up we want to send a beep for non-music events
1460 if (up) {
1461 direction = 0;
1462 }
Jaewan Kim77748b62018-05-03 19:43:33 +09001463 dispatchAdjustVolumeLocked(packageName, pid, uid, asSystemService, stream,
1464 direction, flags);
Jaewan Kim50269362016-12-23 11:22:02 +09001465 } else if (isMute) {
1466 if (down && keyEvent.getRepeatCount() == 0) {
Jaewan Kim77748b62018-05-03 19:43:33 +09001467 dispatchAdjustVolumeLocked(packageName, pid, uid, asSystemService, stream,
1468 AudioManager.ADJUST_TOGGLE_MUTE, flags);
Jaewan Kim50269362016-12-23 11:22:02 +09001469 }
1470 }
1471 }
1472 }
1473
1474 @Override
Jaewan Kim77748b62018-05-03 19:43:33 +09001475 public void dispatchAdjustVolume(String packageName, int suggestedStream, int delta,
1476 int flags) {
1477 final int pid = Binder.getCallingPid();
1478 final int uid = Binder.getCallingUid();
RoboErikb69ffd42014-05-30 14:57:59 -07001479 final long token = Binder.clearCallingIdentity();
1480 try {
1481 synchronized (mLock) {
Jaewan Kim77748b62018-05-03 19:43:33 +09001482 dispatchAdjustVolumeLocked(packageName, pid, uid, false,
1483 suggestedStream, delta, flags);
RoboErikb69ffd42014-05-30 14:57:59 -07001484 }
1485 } finally {
1486 Binder.restoreCallingIdentity(token);
1487 }
1488 }
1489
1490 @Override
RoboErik19c95182014-06-23 15:38:48 -07001491 public void setRemoteVolumeController(IRemoteVolumeController rvc) {
1492 final int pid = Binder.getCallingPid();
1493 final int uid = Binder.getCallingUid();
1494 final long token = Binder.clearCallingIdentity();
1495 try {
John Spurlockeb69e242015-02-17 17:15:04 -05001496 enforceSystemUiPermission("listen for volume changes", pid, uid);
RoboErik19c95182014-06-23 15:38:48 -07001497 mRvc = rvc;
1498 } finally {
1499 Binder.restoreCallingIdentity(token);
1500 }
1501 }
1502
1503 @Override
RoboErikde9ba392014-09-26 12:51:01 -07001504 public boolean isGlobalPriorityActive() {
Jaewan Kim51255012017-02-24 16:19:14 +09001505 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001506 return isGlobalPriorityActiveLocked();
Jaewan Kim51255012017-02-24 16:19:14 +09001507 }
RoboErikde9ba392014-09-26 12:51:01 -07001508 }
1509
1510 @Override
RoboErika278ea72014-04-24 14:49:01 -07001511 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001512 if (!DumpUtils.checkDumpPermission(getContext(), TAG, pw)) return;
RoboErika278ea72014-04-24 14:49:01 -07001513
1514 pw.println("MEDIA SESSION SERVICE (dumpsys media_session)");
1515 pw.println();
1516
1517 synchronized (mLock) {
RoboErika08adb242014-11-21 18:28:18 -08001518 pw.println(mSessionsListeners.size() + " sessions listeners.");
Jaewan Kima7dce192017-02-16 17:10:54 +09001519 pw.println("Global priority session is " + mGlobalPrioritySession);
Jaewan Kim101b4d52017-05-18 13:23:11 +09001520 if (mGlobalPrioritySession != null) {
1521 mGlobalPrioritySession.dump(pw, " ");
1522 }
RoboErik4646d282014-05-13 10:13:04 -07001523 pw.println("User Records:");
Jaewan Kime0ca3f32017-02-16 15:52:39 +09001524 int count = mUserRecords.size();
RoboErika278ea72014-04-24 14:49:01 -07001525 for (int i = 0; i < count; i++) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001526 mUserRecords.valueAt(i).dumpLocked(pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001527 }
Sungsoo Lim875e6972017-11-03 02:22:35 +00001528 mAudioPlayerStateMonitor.dump(getContext(), pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001529 }
1530 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001531
Jaewan Kim7e9e4d92018-02-13 22:20:41 +09001532 /**
Jaewan Kimfed49502018-03-05 17:51:12 +09001533 * Returns if the controller's package is trusted (i.e. has either MEDIA_CONTENT_CONTROL
1534 * permission or an enabled notification listener)
1535 *
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001536 * @param controllerPackageName package name of the controller app
1537 * @param controllerPid pid of the controller app
1538 * @param controllerUid uid of the controller app
Jaewan Kimfed49502018-03-05 17:51:12 +09001539 */
1540 @Override
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001541 public boolean isTrusted(String controllerPackageName, int controllerPid, int controllerUid)
1542 throws RemoteException {
1543 final int uid = Binder.getCallingUid();
Jaewan Kimfed49502018-03-05 17:51:12 +09001544 final long token = Binder.clearCallingIdentity();
1545 try {
Jaewan Kim03cba652018-04-04 16:25:35 +09001546 int controllerUserId = UserHandle.getUserId(controllerUid);
1547 int controllerUidFromPackageName;
1548 try {
1549 controllerUidFromPackageName = getContext().getPackageManager()
1550 .getPackageUidAsUser(controllerPackageName, controllerUserId);
1551 } catch (NameNotFoundException e) {
1552 if (DEBUG) {
1553 Log.d(TAG, "Package " + controllerPackageName + " doesn't exist");
1554 }
1555 return false;
1556 }
1557 if (controllerUidFromPackageName != controllerUid) {
1558 if (DEBUG) {
1559 Log.d(TAG, "Package name " + controllerPackageName
1560 + " doesn't match with the uid " + controllerUid);
1561 }
1562 return false;
1563 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001564 return hasMediaControlPermission(UserHandle.getUserId(uid), controllerPackageName,
1565 controllerPid, controllerUid);
Jaewan Kimfed49502018-03-05 17:51:12 +09001566 } finally {
1567 Binder.restoreCallingIdentity(token);
1568 }
Jaewan Kimfed49502018-03-05 17:51:12 +09001569 }
1570
1571 /**
Jaewan Kim7e9e4d92018-02-13 22:20:41 +09001572 * Called when a {@link android.media.MediaSession2} instance is created.
1573 * <p>
1574 * This does two things.
1575 * 1. Keep the newly created session in the service
1576 * 2. Do sanity check to ensure unique id per package, and return result
1577 *
1578 * @param sessionToken SessionToken2 object in bundled form
1579 * @return {@code true} if the session's id isn't used by the package now. {@code false}
1580 * otherwise.
1581 */
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001582 @Override
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001583 public boolean createSession2(Bundle sessionToken) {
Jaewan Kim129a5622018-03-28 12:19:04 +09001584 if (!USE_MEDIA2_APIS) {
1585 return false;
1586 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001587 final int uid = Binder.getCallingUid();
Christofer Ã…kersten6823d812018-03-22 23:20:39 +09001588 final SessionToken2 token = SessionToken2.fromBundle(sessionToken);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001589 if (token == null || token.getUid() != uid) {
1590 Log.w(TAG, "onSessionCreated failed, expected caller uid=" + token.getUid()
1591 + " but from uid=" + uid);
1592 }
1593 if (DEBUG) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001594 Log.d(TAG, "createSession2: " + token);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001595 }
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001596 synchronized (mLock) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001597 MediaController2 controller = mSessionRecords.get(token);
1598 if (controller != null && controller.isConnected()) {
1599 return false;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001600 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001601 Context context = getContext();
Sungsoo Lim375efa12018-03-02 10:17:08 +09001602 controller = new MediaController2(context, token, context.getMainExecutor(),
1603 new ControllerCallback(token));
1604 if (addSessionRecordLocked(token, controller)) {
1605 postSessionTokensUpdated(UserHandle.getUserId(token.getUid()));
1606 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001607 return true;
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001608 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001609 }
1610
Jaewan Kim7e9e4d92018-02-13 22:20:41 +09001611 /**
1612 * Called when a {@link android.media.MediaSession2} instance is closed. (i.e. destroyed)
1613 * <p>
1614 * Ideally service should know that a session is destroyed through the
1615 * {@link android.media.MediaController2.ControllerCallback#onDisconnected()}, which is
1616 * asynchronous call. However, we also need synchronous way together to address timing
1617 * issue. If the package recreates the session almost immediately, which happens commonly
1618 * for tests, service will reject the creation through {@link #onSessionCreated(Bundle)}
1619 * if the service hasn't notified previous destroy yet. This synchronous API will address
1620 * the issue.
1621 *
1622 * @param sessionToken SessionToken2 object in bundled form
1623 */
Jaewan Kimf7a77062018-01-27 01:34:24 +09001624 @Override
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001625 public void destroySession2(Bundle sessionToken) {
Jaewan Kim129a5622018-03-28 12:19:04 +09001626 if (!USE_MEDIA2_APIS) {
1627 return;
1628 }
Jaewan Kimf7a77062018-01-27 01:34:24 +09001629 final int uid = Binder.getCallingUid();
Christofer Ã…kersten6823d812018-03-22 23:20:39 +09001630 final SessionToken2 token = SessionToken2.fromBundle(sessionToken);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001631 if (token == null || token.getUid() != uid) {
1632 Log.w(TAG, "onSessionDestroyed failed, expected caller uid=" + token.getUid()
1633 + " but from uid=" + uid);
1634 }
1635 if (DEBUG) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001636 Log.d(TAG, "destroySession2 " + token);
Jaewan Kimf7a77062018-01-27 01:34:24 +09001637 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09001638 destroySession2Internal(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001639 }
1640
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001641 // TODO(jaewan): Make this API take userId as an argument (b/73597722)
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001642 @Override
1643 public List<Bundle> getSessionTokens(boolean activeSessionOnly,
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001644 boolean sessionServiceOnly, String packageName) throws RemoteException {
Jaewan Kim129a5622018-03-28 12:19:04 +09001645 if (!USE_MEDIA2_APIS) {
1646 return null;
1647 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001648 final int pid = Binder.getCallingPid();
1649 final int uid = Binder.getCallingUid();
1650 final long token = Binder.clearCallingIdentity();
1651
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001652 List<Bundle> tokens = new ArrayList<>();
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001653 try {
1654 verifySessionsRequest2(UserHandle.getUserId(uid), packageName, pid, uid);
1655 synchronized (mLock) {
1656 for (Map.Entry<SessionToken2, MediaController2> record
1657 : mSessionRecords.entrySet()) {
1658 boolean isSessionService = (record.getKey().getType() != TYPE_SESSION);
1659 boolean isActive = record.getValue() != null;
1660 if ((activeSessionOnly && !isActive)
1661 || (sessionServiceOnly && !isSessionService)) {
1662 continue;
1663 }
1664 tokens.add(record.getKey().toBundle());
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001665 }
1666 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001667 } finally {
1668 Binder.restoreCallingIdentity(token);
Jaewan Kimceb6b6e2018-01-21 20:56:10 +09001669 }
1670 return tokens;
1671 }
1672
Jaewan Kim379e30d2018-01-29 11:57:04 +09001673 @Override
1674 public void addSessionTokensListener(ISessionTokensListener listener, int userId,
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001675 String packageName) throws RemoteException {
Jaewan Kim129a5622018-03-28 12:19:04 +09001676 if (!USE_MEDIA2_APIS) {
1677 return;
1678 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001679 final int pid = Binder.getCallingPid();
1680 final int uid = Binder.getCallingUid();
1681 final long token = Binder.clearCallingIdentity();
1682 try {
1683 int resolvedUserId = verifySessionsRequest2(userId, packageName, pid, uid);
1684 synchronized (mLock) {
1685 final SessionTokensListenerRecord record =
1686 new SessionTokensListenerRecord(listener, resolvedUserId);
1687 try {
1688 listener.asBinder().linkToDeath(record, 0);
1689 } catch (RemoteException e) {
1690 }
1691 mSessionTokensListeners.add(record);
Sungsoo Lim375efa12018-03-02 10:17:08 +09001692 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001693 } finally {
1694 Binder.restoreCallingIdentity(token);
Sungsoo Lim375efa12018-03-02 10:17:08 +09001695 }
Jaewan Kim379e30d2018-01-29 11:57:04 +09001696 }
1697
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001698 // TODO(jaewan): Make this API take userId as an argument (b/73597722)
Jaewan Kim379e30d2018-01-29 11:57:04 +09001699 @Override
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001700 public void removeSessionTokensListener(ISessionTokensListener listener,
1701 String packageName) throws RemoteException {
Jaewan Kim129a5622018-03-28 12:19:04 +09001702 if (!USE_MEDIA2_APIS) {
1703 return;
1704 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001705 final int pid = Binder.getCallingPid();
1706 final int uid = Binder.getCallingUid();
1707 final long token = Binder.clearCallingIdentity();
1708 try {
1709 verifySessionsRequest2(UserHandle.getUserId(uid), packageName, pid, uid);
1710 synchronized (mLock) {
1711 IBinder listenerBinder = listener.asBinder();
1712 for (SessionTokensListenerRecord record : mSessionTokensListeners) {
1713 if (listenerBinder.equals(record.mListener.asBinder())) {
1714 try {
1715 listenerBinder.unlinkToDeath(record, 0);
1716 } catch (NoSuchElementException e) {
1717 }
1718 mSessionTokensListeners.remove(record);
1719 break;
Sungsoo Lim375efa12018-03-02 10:17:08 +09001720 }
Sungsoo Lim375efa12018-03-02 10:17:08 +09001721 }
1722 }
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001723 } finally {
1724 Binder.restoreCallingIdentity(token);
Sungsoo Lim375efa12018-03-02 10:17:08 +09001725 }
Jaewan Kim379e30d2018-01-29 11:57:04 +09001726 }
1727
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001728 // For MediaSession
RoboErik2e7a9162014-06-04 16:53:45 -07001729 private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
1730 final int uid) {
1731 String packageName = null;
1732 if (componentName != null) {
1733 // If they gave us a component name verify they own the
1734 // package
1735 packageName = componentName.getPackageName();
1736 enforcePackageName(packageName, uid);
1737 }
1738 // Check that they can make calls on behalf of the user and
1739 // get the final user id
1740 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
1741 true /* allowAll */, true /* requireFull */, "getSessions", packageName);
1742 // Check if they have the permissions or their component is
1743 // enabled for the user they're calling from.
1744 enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
1745 return resolvedUserId;
1746 }
1747
Hyundo Moonf84c1c02018-03-19 20:33:27 +09001748 // For MediaSession2
1749 private int verifySessionsRequest2(int targetUserId, String callerPackageName,
1750 int callerPid, int callerUid) throws RemoteException {
1751 // Check that they can make calls on behalf of the user and get the final user id.
1752 int resolvedUserId = ActivityManager.handleIncomingUser(callerPid, callerUid,
1753 targetUserId, true /* allowAll */, true /* requireFull */, "getSessionTokens",
1754 callerPackageName);
1755 // Check if they have the permissions or their component is
1756 // enabled for the user they're calling from.
1757 if (!hasMediaControlPermission(
1758 resolvedUserId, callerPackageName, callerPid, callerUid)) {
1759 throw new SecurityException("Missing permission to control media.");
1760 }
1761 return resolvedUserId;
1762 }
1763
1764 // For MediaSession2
1765 private boolean hasMediaControlPermission(int resolvedUserId, String packageName,
1766 int pid, int uid) throws RemoteException {
1767 // Allow API calls from the System UI
1768 if (isCurrentVolumeController(pid, uid)) {
1769 return true;
1770 }
1771
1772 // Check if it's system server or has MEDIA_CONTENT_CONTROL.
1773 // Note that system server doesn't have MEDIA_CONTENT_CONTROL, so we need extra
1774 // check here.
1775 if (uid == Process.SYSTEM_UID || getContext().checkPermission(
1776 android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
1777 == PackageManager.PERMISSION_GRANTED) {
1778 return true;
1779 } else if (DEBUG) {
1780 Log.d(TAG, packageName + " (uid=" + uid + ") hasn't granted MEDIA_CONTENT_CONTROL");
1781 }
1782
1783 // You may not access another user's content as an enabled listener.
1784 final int userId = UserHandle.getUserId(uid);
1785 if (resolvedUserId != userId) {
1786 return false;
1787 }
1788
1789 // TODO(jaewan): (Post-P) Propose NotificationManager#hasEnabledNotificationListener(
1790 // String pkgName) to notification team for optimization
1791 final List<ComponentName> enabledNotificationListeners =
1792 mNotificationManager.getEnabledNotificationListeners(userId);
1793 if (enabledNotificationListeners != null) {
1794 for (int i = 0; i < enabledNotificationListeners.size(); i++) {
1795 if (TextUtils.equals(packageName,
1796 enabledNotificationListeners.get(i).getPackageName())) {
1797 return true;
1798 }
1799 }
1800 }
1801 if (DEBUG) {
1802 Log.d(TAG, packageName + " (uid=" + uid + ") doesn't have an enabled "
1803 + "notification listener");
1804 }
1805 return false;
1806 }
1807
Jaewan Kim77748b62018-05-03 19:43:33 +09001808 private void dispatchAdjustVolumeLocked(String packageName, int pid, int uid,
1809 boolean asSystemService, int suggestedStream, int direction, int flags) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001810 MediaSessionRecord session = isGlobalPriorityActiveLocked() ? mGlobalPrioritySession
1811 : mCurrentFullUserRecord.mPriorityStack.getDefaultVolumeSession();
Jaewan Kim50269362016-12-23 11:22:02 +09001812
RoboErik9c785402014-11-11 16:52:26 -08001813 boolean preferSuggestedStream = false;
1814 if (isValidLocalStreamType(suggestedStream)
1815 && AudioSystem.isStreamActive(suggestedStream, 0)) {
1816 preferSuggestedStream = true;
1817 }
Jaewan Kimb2781e72017-03-02 09:57:09 +09001818 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001819 Log.d(TAG, "Adjusting " + session + " by " + direction + ". flags="
1820 + flags + ", suggestedStream=" + suggestedStream
1821 + ", preferSuggestedStream=" + preferSuggestedStream);
1822 }
RoboErik9c785402014-11-11 16:52:26 -08001823 if (session == null || preferSuggestedStream) {
RoboErik94c716e2014-09-14 13:54:31 -07001824 if ((flags & AudioManager.FLAG_ACTIVE_MEDIA_ONLY) != 0
1825 && !AudioSystem.isStreamActive(AudioManager.STREAM_MUSIC, 0)) {
RoboErik3c45c292014-07-08 16:47:31 -07001826 if (DEBUG) {
1827 Log.d(TAG, "No active session to adjust, skipping media only volume event");
RoboErik3c45c292014-07-08 16:47:31 -07001828 }
RoboErikb7c014c2014-07-22 15:58:22 -07001829 return;
RoboErik3c45c292014-07-08 16:47:31 -07001830 }
Shibin George19e84042016-06-14 20:42:13 +05301831
1832 // Execute mAudioService.adjustSuggestedStreamVolume() on
1833 // handler thread of MediaSessionService.
1834 // This will release the MediaSessionService.mLock sooner and avoid
1835 // a potential deadlock between MediaSessionService.mLock and
1836 // ActivityManagerService lock.
1837 mHandler.post(new Runnable() {
1838 @Override
1839 public void run() {
1840 try {
1841 String packageName = getContext().getOpPackageName();
1842 mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
1843 flags, packageName, TAG);
1844 } catch (RemoteException e) {
1845 Log.e(TAG, "Error adjusting default volume.", e);
Hyundo Moon739d6c22017-09-18 17:01:48 +09001846 } catch (IllegalArgumentException e) {
1847 Log.e(TAG, "Cannot adjust volume: direction=" + direction
1848 + ", suggestedStream=" + suggestedStream + ", flags=" + flags,
1849 e);
Shibin George19e84042016-06-14 20:42:13 +05301850 }
1851 }
1852 });
RoboErikb69ffd42014-05-30 14:57:59 -07001853 } else {
Jaewan Kim21c23e32018-05-17 16:47:31 +09001854 session.adjustVolume(packageName, pid, uid, null, asSystemService,
Jaewan Kim77748b62018-05-03 19:43:33 +09001855 direction, flags, true);
RoboErikb69ffd42014-05-30 14:57:59 -07001856 }
1857 }
1858
Jaewan Kim77748b62018-05-03 19:43:33 +09001859 private void handleVoiceKeyEventLocked(String packageName, int pid, int uid,
1860 boolean asSystemService, KeyEvent keyEvent, boolean needWakeLock) {
RoboErik9a9d0b52014-05-20 14:53:39 -07001861 int action = keyEvent.getAction();
1862 boolean isLongPress = (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0;
1863 if (action == KeyEvent.ACTION_DOWN) {
1864 if (keyEvent.getRepeatCount() == 0) {
1865 mVoiceButtonDown = true;
1866 mVoiceButtonHandled = false;
1867 } else if (mVoiceButtonDown && !mVoiceButtonHandled && isLongPress) {
1868 mVoiceButtonHandled = true;
1869 startVoiceInput(needWakeLock);
1870 }
1871 } else if (action == KeyEvent.ACTION_UP) {
1872 if (mVoiceButtonDown) {
1873 mVoiceButtonDown = false;
1874 if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
1875 // Resend the down then send this event through
1876 KeyEvent downEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_DOWN);
Jaewan Kim77748b62018-05-03 19:43:33 +09001877 dispatchMediaKeyEventLocked(packageName, pid, uid, asSystemService,
1878 downEvent, needWakeLock);
1879 dispatchMediaKeyEventLocked(packageName, pid, uid, asSystemService,
1880 keyEvent, needWakeLock);
RoboErik9a9d0b52014-05-20 14:53:39 -07001881 }
1882 }
1883 }
1884 }
1885
Jaewan Kim77748b62018-05-03 19:43:33 +09001886 private void dispatchMediaKeyEventLocked(String packageName, int pid, int uid,
1887 boolean asSystemService, KeyEvent keyEvent, boolean needWakeLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09001888 MediaSessionRecord session = mCurrentFullUserRecord.getMediaButtonSessionLocked();
RoboErik9a9d0b52014-05-20 14:53:39 -07001889 if (session != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001890 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001891 Log.d(TAG, "Sending " + keyEvent + " to " + session);
RoboErik9a9d0b52014-05-20 14:53:39 -07001892 }
1893 if (needWakeLock) {
1894 mKeyEventReceiver.aquireWakeLockLocked();
1895 }
Jaewan Kim50269362016-12-23 11:22:02 +09001896 // If we don't need a wakelock use -1 as the id so we won't release it later.
Jaewan Kim77748b62018-05-03 19:43:33 +09001897 session.sendMediaButton(packageName, pid, uid, asSystemService, keyEvent,
RoboErik9a9d0b52014-05-20 14:53:39 -07001898 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
Hyundo Moonb1e344e2018-03-22 17:22:14 +09001899 mKeyEventReceiver);
Jaewan Kima7dce192017-02-16 17:10:54 +09001900 if (mCurrentFullUserRecord.mCallback != null) {
Jaewan Kimbd16f452017-02-03 16:21:38 +09001901 try {
Jaewan Kima7dce192017-02-16 17:10:54 +09001902 mCurrentFullUserRecord.mCallback.onMediaKeyEventDispatchedToMediaSession(
Jaewan Kim77748b62018-05-03 19:43:33 +09001903 keyEvent, new MediaSession.Token(session.getControllerBinder()));
Jaewan Kimbd16f452017-02-03 16:21:38 +09001904 } catch (RemoteException e) {
1905 Log.w(TAG, "Failed to send callback", e);
1906 }
1907 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001908 } else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null
1909 || mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
1910 if (needWakeLock) {
1911 mKeyEventReceiver.aquireWakeLockLocked();
1912 }
1913 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
1914 mediaButtonIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1915 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
Jaewan Kim77748b62018-05-03 19:43:33 +09001916 // TODO: Find a way to also send PID/UID in secure way.
1917 String callerPackageName =
1918 (asSystemService) ? getContext().getPackageName() : packageName;
1919 mediaButtonIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, callerPackageName);
Jaewan Kima7dce192017-02-16 17:10:54 +09001920 try {
1921 if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
1922 PendingIntent receiver = mCurrentFullUserRecord.mLastMediaButtonReceiver;
1923 if (DEBUG_KEY_EVENT) {
1924 Log.d(TAG, "Sending " + keyEvent
Jaewan Kim92dea332017-02-02 11:52:08 +09001925 + " to the last known PendingIntent " + receiver);
Jaewan Kima7dce192017-02-16 17:10:54 +09001926 }
1927 receiver.send(getContext(),
1928 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
1929 mediaButtonIntent, mKeyEventReceiver, mHandler);
1930 if (mCurrentFullUserRecord.mCallback != null) {
1931 ComponentName componentName = mCurrentFullUserRecord
1932 .mLastMediaButtonReceiver.getIntent().getComponent();
1933 if (componentName != null) {
1934 mCurrentFullUserRecord.mCallback
1935 .onMediaKeyEventDispatchedToMediaButtonReceiver(
1936 keyEvent, componentName);
Jaewan Kimbd16f452017-02-03 16:21:38 +09001937 }
RoboErikc8f92d12015-01-05 16:48:07 -08001938 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001939 } else {
1940 ComponentName receiver =
1941 mCurrentFullUserRecord.mRestoredMediaButtonReceiver;
1942 if (DEBUG_KEY_EVENT) {
1943 Log.d(TAG, "Sending " + keyEvent + " to the restored intent "
1944 + receiver);
1945 }
1946 mediaButtonIntent.setComponent(receiver);
1947 getContext().sendBroadcastAsUser(mediaButtonIntent,
Jaewan Kim92dea332017-02-02 11:52:08 +09001948 UserHandle.of(mCurrentFullUserRecord
1949 .mRestoredMediaButtonReceiverUserId));
Jaewan Kima7dce192017-02-16 17:10:54 +09001950 if (mCurrentFullUserRecord.mCallback != null) {
1951 mCurrentFullUserRecord.mCallback
1952 .onMediaKeyEventDispatchedToMediaButtonReceiver(
1953 keyEvent, receiver);
1954 }
RoboErikb214efb2014-07-24 13:20:30 -07001955 }
Jaewan Kima7dce192017-02-16 17:10:54 +09001956 } catch (CanceledException e) {
1957 Log.i(TAG, "Error sending key event to media button receiver "
1958 + mCurrentFullUserRecord.mLastMediaButtonReceiver, e);
1959 } catch (RemoteException e) {
1960 Log.w(TAG, "Failed to send callback", e);
RoboErik9a9d0b52014-05-20 14:53:39 -07001961 }
RoboErik9a9d0b52014-05-20 14:53:39 -07001962 }
1963 }
1964
1965 private void startVoiceInput(boolean needWakeLock) {
1966 Intent voiceIntent = null;
1967 // select which type of search to launch:
1968 // - screen on and device unlocked: action is ACTION_WEB_SEARCH
1969 // - device locked or screen off: action is
1970 // ACTION_VOICE_SEARCH_HANDS_FREE
1971 // with EXTRA_SECURE set to true if the device is securely locked
1972 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1973 boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
1974 if (!isLocked && pm.isScreenOn()) {
1975 voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
1976 Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
1977 } else {
1978 voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
1979 voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
1980 isLocked && mKeyguardManager.isKeyguardSecure());
1981 Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
1982 }
1983 // start the search activity
1984 if (needWakeLock) {
1985 mMediaEventWakeLock.acquire();
1986 }
1987 try {
1988 if (voiceIntent != null) {
1989 voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1990 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Jaewan Kim8f729082016-06-21 12:36:26 +09001991 if (DEBUG) Log.d(TAG, "voiceIntent: " + voiceIntent);
RoboErik9a9d0b52014-05-20 14:53:39 -07001992 getContext().startActivityAsUser(voiceIntent, UserHandle.CURRENT);
1993 }
1994 } catch (ActivityNotFoundException e) {
1995 Log.w(TAG, "No activity for search: " + e);
1996 } finally {
1997 if (needWakeLock) {
1998 mMediaEventWakeLock.release();
1999 }
2000 }
2001 }
2002
2003 private boolean isVoiceKey(int keyCode) {
Jaewan Kimba18d8e2017-05-12 17:37:57 +09002004 return keyCode == KeyEvent.KEYCODE_HEADSETHOOK
Jaewan Kimfdb612e2017-07-01 09:23:41 +09002005 || (!mHasFeatureLeanback && keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
RoboErik9a9d0b52014-05-20 14:53:39 -07002006 }
2007
Jeff Brown38d3feb2015-03-19 18:26:30 -07002008 private boolean isUserSetupComplete() {
2009 return Settings.Secure.getIntForUser(getContext().getContentResolver(),
2010 Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
2011 }
2012
RoboErik9c785402014-11-11 16:52:26 -08002013 // we only handle public stream types, which are 0-5
2014 private boolean isValidLocalStreamType(int streamType) {
2015 return streamType >= AudioManager.STREAM_VOICE_CALL
2016 && streamType <= AudioManager.STREAM_NOTIFICATION;
2017 }
2018
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08002019 private class MediaKeyListenerResultReceiver extends ResultReceiver implements Runnable {
Jaewan Kim77748b62018-05-03 19:43:33 +09002020 private final String mPackageName;
2021 private final int mPid;
2022 private final int mUid;
2023 private final boolean mAsSystemService;
2024 private final KeyEvent mKeyEvent;
2025 private final boolean mNeedWakeLock;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08002026 private boolean mHandled;
2027
Jaewan Kim77748b62018-05-03 19:43:33 +09002028 private MediaKeyListenerResultReceiver(String packageName, int pid, int uid,
2029 boolean asSystemService, KeyEvent keyEvent, boolean needWakeLock) {
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08002030 super(mHandler);
2031 mHandler.postDelayed(this, MEDIA_KEY_LISTENER_TIMEOUT);
Jaewan Kim77748b62018-05-03 19:43:33 +09002032 mPackageName = packageName;
2033 mPid = pid;
2034 mUid = uid;
2035 mAsSystemService = asSystemService;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08002036 mKeyEvent = keyEvent;
2037 mNeedWakeLock = needWakeLock;
2038 }
2039
2040 @Override
2041 public void run() {
2042 Log.d(TAG, "The media key listener is timed-out for " + mKeyEvent);
2043 dispatchMediaKeyEvent();
2044 }
2045
2046 @Override
2047 protected void onReceiveResult(int resultCode, Bundle resultData) {
2048 if (resultCode == MediaSessionManager.RESULT_MEDIA_KEY_HANDLED) {
2049 mHandled = true;
2050 mHandler.removeCallbacks(this);
2051 return;
2052 }
2053 dispatchMediaKeyEvent();
2054 }
2055
2056 private void dispatchMediaKeyEvent() {
2057 if (mHandled) {
2058 return;
2059 }
2060 mHandled = true;
2061 mHandler.removeCallbacks(this);
2062 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09002063 if (!isGlobalPriorityActiveLocked()
Jaewan Kim98003d32017-02-24 18:33:04 +09002064 && isVoiceKey(mKeyEvent.getKeyCode())) {
Jaewan Kim77748b62018-05-03 19:43:33 +09002065 handleVoiceKeyEventLocked(mPackageName, mPid, mUid, mAsSystemService,
2066 mKeyEvent, mNeedWakeLock);
Jaewan Kim98003d32017-02-24 18:33:04 +09002067 } else {
Jaewan Kim77748b62018-05-03 19:43:33 +09002068 dispatchMediaKeyEventLocked(mPackageName, mPid, mUid, mAsSystemService,
2069 mKeyEvent, mNeedWakeLock);
Jaewan Kim98003d32017-02-24 18:33:04 +09002070 }
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08002071 }
2072 }
2073 }
2074
RoboErik418c10c2014-05-19 09:25:25 -07002075 private KeyEventWakeLockReceiver mKeyEventReceiver = new KeyEventWakeLockReceiver(mHandler);
2076
RoboErikb214efb2014-07-24 13:20:30 -07002077 class KeyEventWakeLockReceiver extends ResultReceiver implements Runnable,
2078 PendingIntent.OnFinished {
RoboErik418c10c2014-05-19 09:25:25 -07002079 private final Handler mHandler;
2080 private int mRefCount = 0;
2081 private int mLastTimeoutId = 0;
2082
2083 public KeyEventWakeLockReceiver(Handler handler) {
2084 super(handler);
2085 mHandler = handler;
2086 }
2087
2088 public void onTimeout() {
2089 synchronized (mLock) {
2090 if (mRefCount == 0) {
2091 // We've already released it, so just return
2092 return;
2093 }
2094 mLastTimeoutId++;
2095 mRefCount = 0;
2096 releaseWakeLockLocked();
2097 }
2098 }
2099
2100 public void aquireWakeLockLocked() {
2101 if (mRefCount == 0) {
2102 mMediaEventWakeLock.acquire();
2103 }
2104 mRefCount++;
2105 mHandler.removeCallbacks(this);
2106 mHandler.postDelayed(this, WAKELOCK_TIMEOUT);
2107
2108 }
2109
2110 @Override
2111 public void run() {
2112 onTimeout();
2113 }
2114
RoboErik8a2cfc32014-05-16 11:19:38 -07002115 @Override
2116 protected void onReceiveResult(int resultCode, Bundle resultData) {
RoboErik418c10c2014-05-19 09:25:25 -07002117 if (resultCode < mLastTimeoutId) {
2118 // Ignore results from calls that were before the last
2119 // timeout, just in case.
2120 return;
2121 } else {
2122 synchronized (mLock) {
2123 if (mRefCount > 0) {
2124 mRefCount--;
2125 if (mRefCount == 0) {
2126 releaseWakeLockLocked();
2127 }
2128 }
RoboErik8a2cfc32014-05-16 11:19:38 -07002129 }
2130 }
2131 }
RoboErik418c10c2014-05-19 09:25:25 -07002132
2133 private void releaseWakeLockLocked() {
2134 mMediaEventWakeLock.release();
2135 mHandler.removeCallbacks(this);
2136 }
RoboErikb214efb2014-07-24 13:20:30 -07002137
2138 @Override
2139 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
2140 String resultData, Bundle resultExtras) {
2141 onReceiveResult(resultCode, null);
2142 }
RoboErik8a2cfc32014-05-16 11:19:38 -07002143 };
2144
2145 BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
2146 @Override
2147 public void onReceive(Context context, Intent intent) {
2148 if (intent == null) {
2149 return;
2150 }
2151 Bundle extras = intent.getExtras();
2152 if (extras == null) {
2153 return;
2154 }
2155 synchronized (mLock) {
2156 if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)
2157 && mMediaEventWakeLock.isHeld()) {
2158 mMediaEventWakeLock.release();
2159 }
2160 }
2161 }
2162 };
RoboErik01fe6612014-02-13 14:19:04 -08002163 }
2164
RoboErik2e7a9162014-06-04 16:53:45 -07002165 final class MessageHandler extends Handler {
2166 private static final int MSG_SESSIONS_CHANGED = 1;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09002167 private static final int MSG_VOLUME_INITIAL_DOWN = 2;
Sungsoo Lim375efa12018-03-02 10:17:08 +09002168 private static final int MSG_SESSIONS_TOKENS_CHANGED = 3;
Jaewan Kim92dea332017-02-02 11:52:08 +09002169 private final SparseArray<Integer> mIntegerCache = new SparseArray<>();
RoboErik2e7a9162014-06-04 16:53:45 -07002170
2171 @Override
2172 public void handleMessage(Message msg) {
2173 switch (msg.what) {
2174 case MSG_SESSIONS_CHANGED:
Jaewan Kim92dea332017-02-02 11:52:08 +09002175 pushSessionsChanged((int) msg.obj);
RoboErik2e7a9162014-06-04 16:53:45 -07002176 break;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09002177 case MSG_VOLUME_INITIAL_DOWN:
2178 synchronized (mLock) {
Jaewan Kima7dce192017-02-16 17:10:54 +09002179 FullUserRecord user = mUserRecords.get((int) msg.arg1);
Jaewan Kimd61a87b2017-02-17 23:14:10 +09002180 if (user != null && user.mInitialDownVolumeKeyEvent != null) {
2181 dispatchVolumeKeyLongPressLocked(user.mInitialDownVolumeKeyEvent);
2182 // Mark that the key is already handled.
2183 user.mInitialDownVolumeKeyEvent = null;
2184 }
2185 }
2186 break;
Sungsoo Lim375efa12018-03-02 10:17:08 +09002187 case MSG_SESSIONS_TOKENS_CHANGED:
2188 pushSessionTokensChanged((int) msg.obj);
2189 break;
RoboErik2e7a9162014-06-04 16:53:45 -07002190 }
2191 }
2192
Jaewan Kim92dea332017-02-02 11:52:08 +09002193 public void postSessionsChanged(int userId) {
2194 // Use object instead of the arguments when posting message to remove pending requests.
2195 Integer userIdInteger = mIntegerCache.get(userId);
2196 if (userIdInteger == null) {
2197 userIdInteger = Integer.valueOf(userId);
2198 mIntegerCache.put(userId, userIdInteger);
2199 }
2200 removeMessages(MSG_SESSIONS_CHANGED, userIdInteger);
2201 obtainMessage(MSG_SESSIONS_CHANGED, userIdInteger).sendToTarget();
RoboErik2e7a9162014-06-04 16:53:45 -07002202 }
2203 }
Sungsoo Lim117c7f72018-02-13 16:02:24 +09002204
2205 private class ControllerCallback extends MediaController2.ControllerCallback {
2206
2207 private final SessionToken2 mToken;
2208
2209 ControllerCallback(SessionToken2 token) {
2210 mToken = token;
2211 }
2212
2213 @Override
Jaewan Kim3fb60d52018-03-02 19:23:18 +09002214 public void onDisconnected(MediaController2 controller) {
Sungsoo Lim117c7f72018-02-13 16:02:24 +09002215 destroySession2Internal(mToken);
2216 }
2217 };
Sungsoo Lim375efa12018-03-02 10:17:08 +09002218
2219 private final class SessionTokensListenerRecord implements IBinder.DeathRecipient {
2220 private final ISessionTokensListener mListener;
2221 private final int mUserId;
2222
2223 public SessionTokensListenerRecord(ISessionTokensListener listener, int userId) {
2224 mListener = listener;
Jaewan Kim525c88c2018-03-08 10:47:00 +09002225 // TODO(jaewan): should userId be mapped through mFullUserIds? (b/73597722)
Jaewan Kim005e2bb2018-03-02 15:55:12 +09002226 mUserId = userId;
Sungsoo Lim375efa12018-03-02 10:17:08 +09002227 }
2228
2229 @Override
2230 public void binderDied() {
2231 synchronized (mLock) {
2232 mSessionTokensListeners.remove(this);
2233 }
2234 }
2235 }
2236
2237 private void postSessionTokensUpdated(int userId) {
2238 mHandler.obtainMessage(MessageHandler.MSG_SESSIONS_TOKENS_CHANGED, userId).sendToTarget();
2239 }
2240
2241 private void pushSessionTokensChanged(int userId) {
2242 synchronized (mLock) {
2243 List<Bundle> tokens = new ArrayList<>();
2244 for (SessionToken2 token : mSessionRecords.keySet()) {
2245 // TODO(jaewan): Remove the check for UserHandle.USER_ALL (shouldn't happen).
2246 // This happens when called form buildMediaSessionService2List(...).
Jaewan Kim005e2bb2018-03-02 15:55:12 +09002247 // (b/73760382)
Sungsoo Lim375efa12018-03-02 10:17:08 +09002248 if (UserHandle.getUserId(token.getUid()) == userId
2249 || UserHandle.USER_ALL == userId) {
2250 tokens.add(token.toBundle());
2251 }
2252 }
2253
2254 for (SessionTokensListenerRecord record : mSessionTokensListeners) {
Jaewan Kim005e2bb2018-03-02 15:55:12 +09002255 // TODO(jaewan): Should userId be mapped through mFullUserIds? (b/73760382)
Sungsoo Lim375efa12018-03-02 10:17:08 +09002256 if (record.mUserId == userId || record.mUserId == UserHandle.USER_ALL) {
2257 try {
2258 record.mListener.onSessionTokensChanged(tokens);
2259 } catch (RemoteException e) {
2260 Log.w(TAG, "Failed to notify session tokens changed", e);
2261 }
2262 }
2263 }
2264 }
2265 }
2266
2267 private boolean addSessionRecordLocked(SessionToken2 token) {
2268 return addSessionRecordLocked(token, null);
2269 }
2270
2271 private boolean addSessionRecordLocked(SessionToken2 token, MediaController2 controller) {
2272 if (mSessionRecords.containsKey(token) && mSessionRecords.get(token) == controller) {
2273 // The key/value pair already exists, no need to update.
2274 return false;
2275 }
2276
2277 mSessionRecords.put(token, controller);
2278 return true;
2279 }
2280
2281 private boolean removeSessionRecordLocked(SessionToken2 token) {
2282 if (!mSessionRecords.containsKey(token)) {
2283 // The key is already removed, no need to remove.
2284 return false;
2285 }
2286
2287 mSessionRecords.remove(token);
2288 return true;
2289 }
RoboErik01fe6612014-02-13 14:19:04 -08002290}