blob: 2ac5fafa6f6bd1e8559db8e1c44b52a78625fbc4 [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
RoboErika278ea72014-04-24 14:49:01 -070019import android.Manifest;
RoboErik8a2cfc32014-05-16 11:19:38 -070020import android.app.Activity;
RoboErike7880d82014-04-30 12:48:25 -070021import android.app.ActivityManager;
RoboErik9a9d0b52014-05-20 14:53:39 -070022import android.app.KeyguardManager;
RoboErikb214efb2014-07-24 13:20:30 -070023import android.app.PendingIntent;
24import android.app.PendingIntent.CanceledException;
RoboErik9a9d0b52014-05-20 14:53:39 -070025import android.content.ActivityNotFoundException;
RoboErik8a2cfc32014-05-16 11:19:38 -070026import android.content.BroadcastReceiver;
RoboErike7880d82014-04-30 12:48:25 -070027import android.content.ComponentName;
RoboErik6f0e4dd2014-06-17 16:56:27 -070028import android.content.ContentResolver;
RoboErik01fe6612014-02-13 14:19:04 -080029import android.content.Context;
RoboErik8a2cfc32014-05-16 11:19:38 -070030import android.content.Intent;
RoboErika278ea72014-04-24 14:49:01 -070031import android.content.pm.PackageManager;
RoboErik7aef77b2014-08-08 15:56:54 -070032import android.database.ContentObserver;
RoboErik3c45c292014-07-08 16:47:31 -070033import android.media.AudioManager;
John Spurlockeb69e242015-02-17 17:15:04 -050034import android.media.AudioManagerInternal;
RoboErik94c716e2014-09-14 13:54:31 -070035import android.media.AudioSystem;
RoboErikb69ffd42014-05-30 14:57:59 -070036import android.media.IAudioService;
RoboErik19c95182014-06-23 15:38:48 -070037import android.media.IRemoteVolumeController;
RoboErik2e7a9162014-06-04 16:53:45 -070038import android.media.session.IActiveSessionsListener;
RoboErik07c70772014-03-20 13:33:52 -070039import android.media.session.ISession;
40import android.media.session.ISessionCallback;
41import android.media.session.ISessionManager;
Jeff Browndba34ba2014-06-24 20:46:03 -070042import android.media.session.MediaSession;
RoboErik7aef77b2014-08-08 15:56:54 -070043import android.net.Uri;
RoboErik01fe6612014-02-13 14:19:04 -080044import android.os.Binder;
RoboErik8a2cfc32014-05-16 11:19:38 -070045import android.os.Bundle;
RoboErik8ae0f342014-02-24 18:02:08 -080046import android.os.Handler;
RoboErike7880d82014-04-30 12:48:25 -070047import android.os.IBinder;
RoboErik2e7a9162014-06-04 16:53:45 -070048import android.os.Message;
RoboErik8a2cfc32014-05-16 11:19:38 -070049import android.os.PowerManager;
Jaewan Kim8f729082016-06-21 12:36:26 +090050import android.os.Process;
RoboErik01fe6612014-02-13 14:19:04 -080051import android.os.RemoteException;
RoboErik8a2cfc32014-05-16 11:19:38 -070052import android.os.ResultReceiver;
RoboErikb69ffd42014-05-30 14:57:59 -070053import android.os.ServiceManager;
RoboErike7880d82014-04-30 12:48:25 -070054import android.os.UserHandle;
Jaewan Kim8f729082016-06-21 12:36:26 +090055import android.os.UserManager;
RoboErike7880d82014-04-30 12:48:25 -070056import android.provider.Settings;
RoboErik9a9d0b52014-05-20 14:53:39 -070057import android.speech.RecognizerIntent;
RoboErik01fe6612014-02-13 14:19:04 -080058import android.text.TextUtils;
59import android.util.Log;
Jeff Brown38d3feb2015-03-19 18:26:30 -070060import android.util.Slog;
RoboErik4646d282014-05-13 10:13:04 -070061import android.util.SparseArray;
RoboErik8a2cfc32014-05-16 11:19:38 -070062import android.view.KeyEvent;
RoboErik01fe6612014-02-13 14:19:04 -080063
John Spurlockeb69e242015-02-17 17:15:04 -050064import com.android.server.LocalServices;
RoboErik01fe6612014-02-13 14:19:04 -080065import com.android.server.SystemService;
RoboErika278ea72014-04-24 14:49:01 -070066import com.android.server.Watchdog;
67import com.android.server.Watchdog.Monitor;
RoboErik01fe6612014-02-13 14:19:04 -080068
RoboErika278ea72014-04-24 14:49:01 -070069import java.io.FileDescriptor;
70import java.io.PrintWriter;
RoboErik01fe6612014-02-13 14:19:04 -080071import java.util.ArrayList;
Jaewan Kim8f729082016-06-21 12:36:26 +090072import java.util.Arrays;
RoboErike7880d82014-04-30 12:48:25 -070073import java.util.List;
RoboErik01fe6612014-02-13 14:19:04 -080074
75/**
76 * System implementation of MediaSessionManager
77 */
RoboErika278ea72014-04-24 14:49:01 -070078public class MediaSessionService extends SystemService implements Monitor {
RoboErik01fe6612014-02-13 14:19:04 -080079 private static final String TAG = "MediaSessionService";
80 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jaewan Kim5e1476e2016-07-19 22:25:39 +090081 // Leave log for media key event always.
82 private static final boolean DEBUG_MEDIA_KEY_EVENT = DEBUG || true;
RoboErik01fe6612014-02-13 14:19:04 -080083
RoboErik418c10c2014-05-19 09:25:25 -070084 private static final int WAKELOCK_TIMEOUT = 5000;
85
RoboErik2610d712015-01-07 11:10:23 -080086 /* package */final IBinder mICallback = new Binder();
87
RoboErik01fe6612014-02-13 14:19:04 -080088 private final SessionManagerImpl mSessionManagerImpl;
RoboErika8f95142014-05-05 14:23:49 -070089 private final MediaSessionStack mPriorityStack;
RoboErik01fe6612014-02-13 14:19:04 -080090
RoboErik4646d282014-05-13 10:13:04 -070091 private final ArrayList<MediaSessionRecord> mAllSessions = new ArrayList<MediaSessionRecord>();
92 private final SparseArray<UserRecord> mUserRecords = new SparseArray<UserRecord>();
RoboErik2e7a9162014-06-04 16:53:45 -070093 private final ArrayList<SessionsListenerRecord> mSessionsListeners
94 = new ArrayList<SessionsListenerRecord>();
RoboErik01fe6612014-02-13 14:19:04 -080095 private final Object mLock = new Object();
RoboErik2e7a9162014-06-04 16:53:45 -070096 private final MessageHandler mHandler = new MessageHandler();
RoboErik8a2cfc32014-05-16 11:19:38 -070097 private final PowerManager.WakeLock mMediaEventWakeLock;
RoboErik01fe6612014-02-13 14:19:04 -080098
RoboErik9a9d0b52014-05-20 14:53:39 -070099 private KeyguardManager mKeyguardManager;
RoboErikb69ffd42014-05-30 14:57:59 -0700100 private IAudioService mAudioService;
John Spurlockeb69e242015-02-17 17:15:04 -0500101 private AudioManagerInternal mAudioManagerInternal;
RoboErik6f0e4dd2014-06-17 16:56:27 -0700102 private ContentResolver mContentResolver;
RoboErik7aef77b2014-08-08 15:56:54 -0700103 private SettingsObserver mSettingsObserver;
RoboErik9a9d0b52014-05-20 14:53:39 -0700104
Jaewan Kim8f729082016-06-21 12:36:26 +0900105 // List of user IDs running in the foreground.
106 // Multiple users can be in the foreground if the work profile is on.
107 private final List<Integer> mCurrentUserIdList = new ArrayList<>();
RoboErike7880d82014-04-30 12:48:25 -0700108
RoboErik19c95182014-06-23 15:38:48 -0700109 // Used to notify system UI when remote volume was changed. TODO find a
110 // better way to handle this.
111 private IRemoteVolumeController mRvc;
112
RoboErik01fe6612014-02-13 14:19:04 -0800113 public MediaSessionService(Context context) {
114 super(context);
115 mSessionManagerImpl = new SessionManagerImpl();
RoboErika8f95142014-05-05 14:23:49 -0700116 mPriorityStack = new MediaSessionStack();
RoboErik8a2cfc32014-05-16 11:19:38 -0700117 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
118 mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
RoboErik01fe6612014-02-13 14:19:04 -0800119 }
120
121 @Override
122 public void onStart() {
123 publishBinderService(Context.MEDIA_SESSION_SERVICE, mSessionManagerImpl);
RoboErika278ea72014-04-24 14:49:01 -0700124 Watchdog.getInstance().addMonitor(this);
RoboErik9a9d0b52014-05-20 14:53:39 -0700125 mKeyguardManager =
126 (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
RoboErikb69ffd42014-05-30 14:57:59 -0700127 mAudioService = getAudioService();
John Spurlockeb69e242015-02-17 17:15:04 -0500128 mAudioManagerInternal = LocalServices.getService(AudioManagerInternal.class);
RoboErik6f0e4dd2014-06-17 16:56:27 -0700129 mContentResolver = getContext().getContentResolver();
RoboErik7aef77b2014-08-08 15:56:54 -0700130 mSettingsObserver = new SettingsObserver();
131 mSettingsObserver.observe();
RoboErikc8f92d12015-01-05 16:48:07 -0800132
133 updateUser();
RoboErikb69ffd42014-05-30 14:57:59 -0700134 }
135
136 private IAudioService getAudioService() {
137 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
138 return IAudioService.Stub.asInterface(b);
RoboErik07c70772014-03-20 13:33:52 -0700139 }
140
RoboErika8f95142014-05-05 14:23:49 -0700141 public void updateSession(MediaSessionRecord record) {
RoboErike7880d82014-04-30 12:48:25 -0700142 synchronized (mLock) {
RoboErik4646d282014-05-13 10:13:04 -0700143 if (!mAllSessions.contains(record)) {
144 Log.d(TAG, "Unknown session updated. Ignoring.");
145 return;
146 }
RoboErika8f95142014-05-05 14:23:49 -0700147 mPriorityStack.onSessionStateChange(record);
RoboErike7880d82014-04-30 12:48:25 -0700148 }
RoboErik2e7a9162014-06-04 16:53:45 -0700149 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, record.getUserId(), 0);
RoboErike7880d82014-04-30 12:48:25 -0700150 }
151
RoboErik9c5b7cb2015-01-15 15:09:09 -0800152 /**
Hyundo Moona055f132017-01-13 15:31:06 +0900153 * Tells the system UI that volume has changed on an active remote session.
RoboErik9c5b7cb2015-01-15 15:09:09 -0800154 */
155 public void notifyRemoteVolumeChanged(int flags, MediaSessionRecord session) {
Hyundo Moona055f132017-01-13 15:31:06 +0900156 if (mRvc == null || !session.isActive()) {
RoboErik9c5b7cb2015-01-15 15:09:09 -0800157 return;
158 }
159 try {
160 mRvc.remoteVolumeChanged(session.getControllerBinder(), flags);
161 } catch (Exception e) {
162 Log.wtf(TAG, "Error sending volume change to system UI.", e);
163 }
164 }
165
RoboErika8f95142014-05-05 14:23:49 -0700166 public void onSessionPlaystateChange(MediaSessionRecord record, int oldState, int newState) {
RoboErik2e7a9162014-06-04 16:53:45 -0700167 boolean updateSessions = false;
RoboErika8f95142014-05-05 14:23:49 -0700168 synchronized (mLock) {
RoboErik4646d282014-05-13 10:13:04 -0700169 if (!mAllSessions.contains(record)) {
170 Log.d(TAG, "Unknown session changed playback state. Ignoring.");
171 return;
172 }
RoboErik2e7a9162014-06-04 16:53:45 -0700173 updateSessions = mPriorityStack.onPlaystateChange(record, oldState, newState);
174 }
175 if (updateSessions) {
176 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, record.getUserId(), 0);
RoboErika8f95142014-05-05 14:23:49 -0700177 }
178 }
179
RoboErik19c95182014-06-23 15:38:48 -0700180 public void onSessionPlaybackTypeChanged(MediaSessionRecord record) {
181 synchronized (mLock) {
182 if (!mAllSessions.contains(record)) {
183 Log.d(TAG, "Unknown session changed playback type. Ignoring.");
184 return;
185 }
186 pushRemoteVolumeUpdateLocked(record.getUserId());
187 }
188 }
189
RoboErika278ea72014-04-24 14:49:01 -0700190 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900191 public void onStartUser(int userId) {
192 if (DEBUG) Log.d(TAG, "onStartUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700193 updateUser();
194 }
195
196 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900197 public void onSwitchUser(int userId) {
198 if (DEBUG) Log.d(TAG, "onSwitchUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700199 updateUser();
200 }
201
202 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900203 public void onStopUser(int userId) {
204 if (DEBUG) Log.d(TAG, "onStopUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700205 synchronized (mLock) {
Jaewan Kim8f729082016-06-21 12:36:26 +0900206 UserRecord user = mUserRecords.get(userId);
RoboErik4646d282014-05-13 10:13:04 -0700207 if (user != null) {
208 destroyUserLocked(user);
209 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900210 updateUser();
RoboErik4646d282014-05-13 10:13:04 -0700211 }
212 }
213
214 @Override
RoboErika278ea72014-04-24 14:49:01 -0700215 public void monitor() {
216 synchronized (mLock) {
217 // Check for deadlock
218 }
219 }
220
RoboErik4646d282014-05-13 10:13:04 -0700221 protected void enforcePhoneStatePermission(int pid, int uid) {
222 if (getContext().checkPermission(android.Manifest.permission.MODIFY_PHONE_STATE, pid, uid)
223 != PackageManager.PERMISSION_GRANTED) {
224 throw new SecurityException("Must hold the MODIFY_PHONE_STATE permission.");
225 }
226 }
227
RoboErik01fe6612014-02-13 14:19:04 -0800228 void sessionDied(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700229 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800230 destroySessionLocked(session);
231 }
232 }
233
234 void destroySession(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700235 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800236 destroySessionLocked(session);
237 }
238 }
239
RoboErik4646d282014-05-13 10:13:04 -0700240 private void updateUser() {
241 synchronized (mLock) {
Jaewan Kim8f729082016-06-21 12:36:26 +0900242 UserManager manager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
243 int currentUser = ActivityManager.getCurrentUser();
Dongwon Kang8cf39c52016-07-29 13:20:39 -0700244 // Include all profiles even though they aren't yet enabled to handle work profile case.
245 int[] userIds = manager.getProfileIdsWithDisabled(currentUser);
Jaewan Kim8f729082016-06-21 12:36:26 +0900246 mCurrentUserIdList.clear();
247 if (userIds != null && userIds.length > 0) {
248 for (int userId : userIds) {
249 mCurrentUserIdList.add(userId);
RoboErik4646d282014-05-13 10:13:04 -0700250 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900251 } else {
252 // This shouldn't happen.
253 Log.w(TAG, "Failed to get enabled profiles.");
254 mCurrentUserIdList.add(currentUser);
255 }
256 for (int userId : mCurrentUserIdList) {
257 if (mUserRecords.get(userId) == null) {
258 mUserRecords.put(userId, new UserRecord(getContext(), userId));
259 }
RoboErik4646d282014-05-13 10:13:04 -0700260 }
261 }
262 }
263
RoboErik7aef77b2014-08-08 15:56:54 -0700264 private void updateActiveSessionListeners() {
265 synchronized (mLock) {
266 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
267 SessionsListenerRecord listener = mSessionsListeners.get(i);
268 try {
269 enforceMediaPermissions(listener.mComponentName, listener.mPid, listener.mUid,
270 listener.mUserId);
271 } catch (SecurityException e) {
272 Log.i(TAG, "ActiveSessionsListener " + listener.mComponentName
273 + " is no longer authorized. Disconnecting.");
274 mSessionsListeners.remove(i);
275 try {
276 listener.mListener
277 .onActiveSessionsChanged(new ArrayList<MediaSession.Token>());
278 } catch (Exception e1) {
279 // ignore
280 }
281 }
282 }
283 }
284 }
285
RoboErik4646d282014-05-13 10:13:04 -0700286 /**
287 * Stop the user and unbind from everything.
288 *
289 * @param user The user to dispose of
290 */
291 private void destroyUserLocked(UserRecord user) {
RoboErik4646d282014-05-13 10:13:04 -0700292 user.destroyLocked();
293 mUserRecords.remove(user.mUserId);
294 }
295
296 /*
297 * When a session is removed several things need to happen.
298 * 1. We need to remove it from the relevant user.
299 * 2. We need to remove it from the priority stack.
300 * 3. We need to remove it from all sessions.
301 * 4. If this is the system priority session we need to clear it.
302 * 5. We need to unlink to death from the cb binder
303 * 6. We need to tell the session to do any final cleanup (onDestroy)
304 */
RoboErik01fe6612014-02-13 14:19:04 -0800305 private void destroySessionLocked(MediaSessionRecord session) {
Insun Kang30be970a2015-11-26 15:35:44 +0900306 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900307 Log.d(TAG, "Destroying " + session);
Insun Kang30be970a2015-11-26 15:35:44 +0900308 }
RoboErik4646d282014-05-13 10:13:04 -0700309 int userId = session.getUserId();
310 UserRecord user = mUserRecords.get(userId);
311 if (user != null) {
312 user.removeSessionLocked(session);
313 }
314
RoboErika8f95142014-05-05 14:23:49 -0700315 mPriorityStack.removeSession(session);
RoboErik4646d282014-05-13 10:13:04 -0700316 mAllSessions.remove(session);
RoboErik4646d282014-05-13 10:13:04 -0700317
318 try {
319 session.getCallback().asBinder().unlinkToDeath(session, 0);
320 } catch (Exception e) {
321 // ignore exceptions while destroying a session.
322 }
323 session.onDestroy();
RoboErik2e7a9162014-06-04 16:53:45 -0700324
325 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, session.getUserId(), 0);
RoboErik01fe6612014-02-13 14:19:04 -0800326 }
327
328 private void enforcePackageName(String packageName, int uid) {
329 if (TextUtils.isEmpty(packageName)) {
330 throw new IllegalArgumentException("packageName may not be empty");
331 }
332 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
333 final int packageCount = packages.length;
334 for (int i = 0; i < packageCount; i++) {
335 if (packageName.equals(packages[i])) {
336 return;
337 }
338 }
339 throw new IllegalArgumentException("packageName is not owned by the calling process");
340 }
341
RoboErike7880d82014-04-30 12:48:25 -0700342 /**
343 * Checks a caller's authorization to register an IRemoteControlDisplay.
344 * Authorization is granted if one of the following is true:
345 * <ul>
346 * <li>the caller has android.Manifest.permission.MEDIA_CONTENT_CONTROL
347 * permission</li>
RoboErika5b02322014-05-07 17:05:49 -0700348 * <li>the caller's listener is one of the enabled notification listeners
349 * for the caller's user</li>
RoboErike7880d82014-04-30 12:48:25 -0700350 * </ul>
351 */
RoboErika5b02322014-05-07 17:05:49 -0700352 private void enforceMediaPermissions(ComponentName compName, int pid, int uid,
353 int resolvedUserId) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500354 if (isCurrentVolumeController(uid, pid)) return;
RoboErike7880d82014-04-30 12:48:25 -0700355 if (getContext()
356 .checkPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
357 != PackageManager.PERMISSION_GRANTED
RoboErika5b02322014-05-07 17:05:49 -0700358 && !isEnabledNotificationListener(compName, UserHandle.getUserId(uid),
359 resolvedUserId)) {
RoboErike7880d82014-04-30 12:48:25 -0700360 throw new SecurityException("Missing permission to control media.");
361 }
362 }
363
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500364 private boolean isCurrentVolumeController(int uid, int pid) {
365 return getContext().checkPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
366 pid, uid) == PackageManager.PERMISSION_GRANTED;
John Spurlockbe19ed02015-02-22 10:57:55 -0500367 }
368
369 private void enforceSystemUiPermission(String action, int pid, int uid) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500370 if (!isCurrentVolumeController(uid, pid)) {
RoboErik19c95182014-06-23 15:38:48 -0700371 throw new SecurityException("Only system ui may " + action);
372 }
373 }
374
RoboErika5b02322014-05-07 17:05:49 -0700375 /**
376 * This checks if the component is an enabled notification listener for the
377 * specified user. Enabled components may only operate on behalf of the user
378 * they're running as.
379 *
380 * @param compName The component that is enabled.
381 * @param userId The user id of the caller.
382 * @param forUserId The user id they're making the request on behalf of.
383 * @return True if the component is enabled, false otherwise
384 */
385 private boolean isEnabledNotificationListener(ComponentName compName, int userId,
386 int forUserId) {
387 if (userId != forUserId) {
388 // You may not access another user's content as an enabled listener.
389 return false;
390 }
RoboErik51fa6bc2014-06-20 14:59:58 -0700391 if (DEBUG) {
392 Log.d(TAG, "Checking if enabled notification listener " + compName);
393 }
RoboErike7880d82014-04-30 12:48:25 -0700394 if (compName != null) {
RoboErik6f0e4dd2014-06-17 16:56:27 -0700395 final String enabledNotifListeners = Settings.Secure.getStringForUser(mContentResolver,
RoboErike7880d82014-04-30 12:48:25 -0700396 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
RoboErika5b02322014-05-07 17:05:49 -0700397 userId);
RoboErike7880d82014-04-30 12:48:25 -0700398 if (enabledNotifListeners != null) {
399 final String[] components = enabledNotifListeners.split(":");
400 for (int i = 0; i < components.length; i++) {
401 final ComponentName component =
402 ComponentName.unflattenFromString(components[i]);
403 if (component != null) {
404 if (compName.equals(component)) {
405 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900406 Log.d(TAG, "ok to get sessions. " + component +
RoboErike7880d82014-04-30 12:48:25 -0700407 " is authorized notification listener");
408 }
409 return true;
410 }
411 }
412 }
413 }
414 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900415 Log.d(TAG, "not ok to get sessions. " + compName +
RoboErika5b02322014-05-07 17:05:49 -0700416 " is not in list of ENABLED_NOTIFICATION_LISTENERS for user " + userId);
RoboErike7880d82014-04-30 12:48:25 -0700417 }
418 }
419 return false;
420 }
421
RoboErika5b02322014-05-07 17:05:49 -0700422 private MediaSessionRecord createSessionInternal(int callerPid, int callerUid, int userId,
RoboErik4646d282014-05-13 10:13:04 -0700423 String callerPackageName, ISessionCallback cb, String tag) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800424 synchronized (mLock) {
RoboErika5b02322014-05-07 17:05:49 -0700425 return createSessionLocked(callerPid, callerUid, userId, callerPackageName, cb, tag);
RoboErik01fe6612014-02-13 14:19:04 -0800426 }
427 }
428
RoboErik4646d282014-05-13 10:13:04 -0700429 /*
430 * When a session is created the following things need to happen.
RoboErik8a2cfc32014-05-16 11:19:38 -0700431 * 1. Its callback binder needs a link to death
RoboErik4646d282014-05-13 10:13:04 -0700432 * 2. It needs to be added to all sessions.
433 * 3. It needs to be added to the priority stack.
434 * 4. It needs to be added to the relevant user record.
435 */
RoboErika5b02322014-05-07 17:05:49 -0700436 private MediaSessionRecord createSessionLocked(int callerPid, int callerUid, int userId,
437 String callerPackageName, ISessionCallback cb, String tag) {
RoboErik4646d282014-05-13 10:13:04 -0700438
Dongwon Kang8cf39c52016-07-29 13:20:39 -0700439 UserRecord user = mUserRecords.get(userId);
440 if (user == null) {
441 Log.wtf(TAG, "Request from invalid user: " + userId);
442 throw new RuntimeException("Session request from invalid user.");
443 }
444
RoboErika5b02322014-05-07 17:05:49 -0700445 final MediaSessionRecord session = new MediaSessionRecord(callerPid, callerUid, userId,
446 callerPackageName, cb, tag, this, mHandler);
RoboErik01fe6612014-02-13 14:19:04 -0800447 try {
448 cb.asBinder().linkToDeath(session, 0);
449 } catch (RemoteException e) {
450 throw new RuntimeException("Media Session owner died prematurely.", e);
451 }
RoboErik4646d282014-05-13 10:13:04 -0700452
453 mAllSessions.add(session);
Jaewan Kim8f729082016-06-21 12:36:26 +0900454 mPriorityStack.addSession(session, mCurrentUserIdList.contains(userId));
RoboErik4646d282014-05-13 10:13:04 -0700455 user.addSessionLocked(session);
456
RoboErik2e7a9162014-06-04 16:53:45 -0700457 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, userId, 0);
458
RoboErik01fe6612014-02-13 14:19:04 -0800459 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900460 Log.d(TAG, "Created session for " + callerPackageName + " with tag " + tag);
RoboErik01fe6612014-02-13 14:19:04 -0800461 }
462 return session;
463 }
464
RoboErik2e7a9162014-06-04 16:53:45 -0700465 private int findIndexOfSessionsListenerLocked(IActiveSessionsListener listener) {
466 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
RoboErika08adb242014-11-21 18:28:18 -0800467 if (mSessionsListeners.get(i).mListener.asBinder() == listener.asBinder()) {
RoboErik2e7a9162014-06-04 16:53:45 -0700468 return i;
469 }
470 }
471 return -1;
472 }
473
RoboErik2e7a9162014-06-04 16:53:45 -0700474 private void pushSessionsChanged(int userId) {
475 synchronized (mLock) {
476 List<MediaSessionRecord> records = mPriorityStack.getActiveSessions(userId);
477 int size = records.size();
RoboErik870c5a62014-12-02 15:08:26 -0800478 if (size > 0 && records.get(0).isPlaybackActive(false)) {
RoboErikb214efb2014-07-24 13:20:30 -0700479 rememberMediaButtonReceiverLocked(records.get(0));
RoboErik6f0e4dd2014-06-17 16:56:27 -0700480 }
Jeff Browndba34ba2014-06-24 20:46:03 -0700481 ArrayList<MediaSession.Token> tokens = new ArrayList<MediaSession.Token>();
RoboErik2e7a9162014-06-04 16:53:45 -0700482 for (int i = 0; i < size; i++) {
Jeff Browndba34ba2014-06-24 20:46:03 -0700483 tokens.add(new MediaSession.Token(records.get(i).getControllerBinder()));
RoboErik2e7a9162014-06-04 16:53:45 -0700484 }
RoboErik19c95182014-06-23 15:38:48 -0700485 pushRemoteVolumeUpdateLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700486 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
487 SessionsListenerRecord record = mSessionsListeners.get(i);
488 if (record.mUserId == UserHandle.USER_ALL || record.mUserId == userId) {
489 try {
490 record.mListener.onActiveSessionsChanged(tokens);
491 } catch (RemoteException e) {
492 Log.w(TAG, "Dead ActiveSessionsListener in pushSessionsChanged, removing",
493 e);
494 mSessionsListeners.remove(i);
495 }
496 }
497 }
498 }
499 }
500
RoboErik19c95182014-06-23 15:38:48 -0700501 private void pushRemoteVolumeUpdateLocked(int userId) {
502 if (mRvc != null) {
503 try {
504 MediaSessionRecord record = mPriorityStack.getDefaultRemoteSession(userId);
505 mRvc.updateRemoteController(record == null ? null : record.getControllerBinder());
506 } catch (RemoteException e) {
507 Log.wtf(TAG, "Error sending default remote volume to sys ui.", e);
508 }
509 }
510 }
511
RoboErikb214efb2014-07-24 13:20:30 -0700512 private void rememberMediaButtonReceiverLocked(MediaSessionRecord record) {
513 PendingIntent receiver = record.getMediaButtonReceiver();
514 UserRecord user = mUserRecords.get(record.getUserId());
515 if (receiver != null && user != null) {
516 user.mLastMediaButtonReceiver = receiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800517 ComponentName component = receiver.getIntent().getComponent();
518 if (component != null && record.getPackageName().equals(component.getPackageName())) {
519 Settings.Secure.putStringForUser(mContentResolver,
520 Settings.System.MEDIA_BUTTON_RECEIVER, component.flattenToString(),
521 record.getUserId());
522 }
RoboErik6f0e4dd2014-06-17 16:56:27 -0700523 }
524 }
525
RoboErik4646d282014-05-13 10:13:04 -0700526 /**
527 * Information about a particular user. The contents of this object is
528 * guarded by mLock.
529 */
530 final class UserRecord {
531 private final int mUserId;
RoboErik4646d282014-05-13 10:13:04 -0700532 private final ArrayList<MediaSessionRecord> mSessions = new ArrayList<MediaSessionRecord>();
RoboErikc8f92d12015-01-05 16:48:07 -0800533 private final Context mContext;
RoboErikb214efb2014-07-24 13:20:30 -0700534 private PendingIntent mLastMediaButtonReceiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800535 private ComponentName mRestoredMediaButtonReceiver;
RoboErik4646d282014-05-13 10:13:04 -0700536
537 public UserRecord(Context context, int userId) {
RoboErikc8f92d12015-01-05 16:48:07 -0800538 mContext = context;
RoboErik4646d282014-05-13 10:13:04 -0700539 mUserId = userId;
RoboErikc8f92d12015-01-05 16:48:07 -0800540 restoreMediaButtonReceiver();
RoboErik4646d282014-05-13 10:13:04 -0700541 }
542
RoboErik4646d282014-05-13 10:13:04 -0700543 public void destroyLocked() {
544 for (int i = mSessions.size() - 1; i >= 0; i--) {
545 MediaSessionRecord session = mSessions.get(i);
546 MediaSessionService.this.destroySessionLocked(session);
RoboErik4646d282014-05-13 10:13:04 -0700547 }
548 }
549
RoboErik4646d282014-05-13 10:13:04 -0700550 public ArrayList<MediaSessionRecord> getSessionsLocked() {
551 return mSessions;
552 }
553
554 public void addSessionLocked(MediaSessionRecord session) {
555 mSessions.add(session);
RoboErik4646d282014-05-13 10:13:04 -0700556 }
557
558 public void removeSessionLocked(MediaSessionRecord session) {
559 mSessions.remove(session);
RoboErik4646d282014-05-13 10:13:04 -0700560 }
561
562 public void dumpLocked(PrintWriter pw, String prefix) {
563 pw.println(prefix + "Record for user " + mUserId);
564 String indent = prefix + " ";
RoboErikb214efb2014-07-24 13:20:30 -0700565 pw.println(indent + "MediaButtonReceiver:" + mLastMediaButtonReceiver);
RoboErikc8f92d12015-01-05 16:48:07 -0800566 pw.println(indent + "Restored ButtonReceiver:" + mRestoredMediaButtonReceiver);
Jeff Brown01a500e2014-07-10 22:50:50 -0700567 int size = mSessions.size();
RoboErik4646d282014-05-13 10:13:04 -0700568 pw.println(indent + size + " Sessions:");
569 for (int i = 0; i < size; i++) {
RoboErikaa4e23b2014-07-24 18:35:11 -0700570 // Just print the short version, the full session dump will
RoboErik4646d282014-05-13 10:13:04 -0700571 // already be in the list of all sessions.
RoboErikaa4e23b2014-07-24 18:35:11 -0700572 pw.println(indent + mSessions.get(i).toString());
RoboErik4646d282014-05-13 10:13:04 -0700573 }
574 }
RoboErikc8f92d12015-01-05 16:48:07 -0800575
576 private void restoreMediaButtonReceiver() {
577 String receiverName = Settings.Secure.getStringForUser(mContentResolver,
Jaewan Kim8f729082016-06-21 12:36:26 +0900578 Settings.System.MEDIA_BUTTON_RECEIVER, mUserId);
RoboErikc8f92d12015-01-05 16:48:07 -0800579 if (!TextUtils.isEmpty(receiverName)) {
580 ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
581 if (eventReceiver == null) {
582 // an invalid name was persisted
583 return;
584 }
585 mRestoredMediaButtonReceiver = eventReceiver;
586 }
587 }
RoboErik4646d282014-05-13 10:13:04 -0700588 }
589
RoboErik2e7a9162014-06-04 16:53:45 -0700590 final class SessionsListenerRecord implements IBinder.DeathRecipient {
591 private final IActiveSessionsListener mListener;
RoboErik7aef77b2014-08-08 15:56:54 -0700592 private final ComponentName mComponentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700593 private final int mUserId;
RoboErik7aef77b2014-08-08 15:56:54 -0700594 private final int mPid;
595 private final int mUid;
RoboErik2e7a9162014-06-04 16:53:45 -0700596
RoboErik7aef77b2014-08-08 15:56:54 -0700597 public SessionsListenerRecord(IActiveSessionsListener listener,
598 ComponentName componentName,
599 int userId, int pid, int uid) {
RoboErik2e7a9162014-06-04 16:53:45 -0700600 mListener = listener;
RoboErik7aef77b2014-08-08 15:56:54 -0700601 mComponentName = componentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700602 mUserId = userId;
RoboErik7aef77b2014-08-08 15:56:54 -0700603 mPid = pid;
604 mUid = uid;
RoboErik2e7a9162014-06-04 16:53:45 -0700605 }
606
607 @Override
608 public void binderDied() {
609 synchronized (mLock) {
610 mSessionsListeners.remove(this);
611 }
612 }
613 }
614
RoboErik7aef77b2014-08-08 15:56:54 -0700615 final class SettingsObserver extends ContentObserver {
616 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(
617 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
618
619 private SettingsObserver() {
620 super(null);
621 }
622
623 private void observe() {
624 mContentResolver.registerContentObserver(mSecureSettingsUri,
625 false, this, UserHandle.USER_ALL);
626 }
627
628 @Override
629 public void onChange(boolean selfChange, Uri uri) {
630 updateActiveSessionListeners();
631 }
632 }
633
RoboErik07c70772014-03-20 13:33:52 -0700634 class SessionManagerImpl extends ISessionManager.Stub {
RoboErik8a2cfc32014-05-16 11:19:38 -0700635 private static final String EXTRA_WAKELOCK_ACQUIRED =
636 "android.media.AudioService.WAKELOCK_ACQUIRED";
637 private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; // magic number
638
RoboErik9a9d0b52014-05-20 14:53:39 -0700639 private boolean mVoiceButtonDown = false;
640 private boolean mVoiceButtonHandled = false;
641
RoboErik07c70772014-03-20 13:33:52 -0700642 @Override
RoboErika5b02322014-05-07 17:05:49 -0700643 public ISession createSession(String packageName, ISessionCallback cb, String tag,
644 int userId) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800645 final int pid = Binder.getCallingPid();
646 final int uid = Binder.getCallingUid();
647 final long token = Binder.clearCallingIdentity();
648 try {
649 enforcePackageName(packageName, uid);
RoboErika5b02322014-05-07 17:05:49 -0700650 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
651 false /* allowAll */, true /* requireFull */, "createSession", packageName);
RoboErik01fe6612014-02-13 14:19:04 -0800652 if (cb == null) {
653 throw new IllegalArgumentException("Controller callback cannot be null");
654 }
RoboErika5b02322014-05-07 17:05:49 -0700655 return createSessionInternal(pid, uid, resolvedUserId, packageName, cb, tag)
656 .getSessionBinder();
RoboErike7880d82014-04-30 12:48:25 -0700657 } finally {
658 Binder.restoreCallingIdentity(token);
659 }
660 }
661
662 @Override
RoboErika5b02322014-05-07 17:05:49 -0700663 public List<IBinder> getSessions(ComponentName componentName, int userId) {
RoboErike7880d82014-04-30 12:48:25 -0700664 final int pid = Binder.getCallingPid();
665 final int uid = Binder.getCallingUid();
666 final long token = Binder.clearCallingIdentity();
667
668 try {
RoboErik2e7a9162014-06-04 16:53:45 -0700669 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
RoboErike7880d82014-04-30 12:48:25 -0700670 ArrayList<IBinder> binders = new ArrayList<IBinder>();
671 synchronized (mLock) {
RoboErika8f95142014-05-05 14:23:49 -0700672 ArrayList<MediaSessionRecord> records = mPriorityStack
RoboErika5b02322014-05-07 17:05:49 -0700673 .getActiveSessions(resolvedUserId);
RoboErika8f95142014-05-05 14:23:49 -0700674 int size = records.size();
675 for (int i = 0; i < size; i++) {
676 binders.add(records.get(i).getControllerBinder().asBinder());
RoboErike7880d82014-04-30 12:48:25 -0700677 }
678 }
679 return binders;
RoboErik01fe6612014-02-13 14:19:04 -0800680 } finally {
681 Binder.restoreCallingIdentity(token);
682 }
683 }
RoboErika278ea72014-04-24 14:49:01 -0700684
RoboErik2e7a9162014-06-04 16:53:45 -0700685 @Override
686 public void addSessionsListener(IActiveSessionsListener listener,
687 ComponentName componentName, int userId) throws RemoteException {
688 final int pid = Binder.getCallingPid();
689 final int uid = Binder.getCallingUid();
690 final long token = Binder.clearCallingIdentity();
691
692 try {
693 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
694 synchronized (mLock) {
695 int index = findIndexOfSessionsListenerLocked(listener);
696 if (index != -1) {
697 Log.w(TAG, "ActiveSessionsListener is already added, ignoring");
698 return;
699 }
700 SessionsListenerRecord record = new SessionsListenerRecord(listener,
RoboErik7aef77b2014-08-08 15:56:54 -0700701 componentName, resolvedUserId, pid, uid);
RoboErik2e7a9162014-06-04 16:53:45 -0700702 try {
703 listener.asBinder().linkToDeath(record, 0);
704 } catch (RemoteException e) {
705 Log.e(TAG, "ActiveSessionsListener is dead, ignoring it", e);
706 return;
707 }
708 mSessionsListeners.add(record);
709 }
710 } finally {
711 Binder.restoreCallingIdentity(token);
712 }
713 }
714
715 @Override
716 public void removeSessionsListener(IActiveSessionsListener listener)
717 throws RemoteException {
718 synchronized (mLock) {
719 int index = findIndexOfSessionsListenerLocked(listener);
720 if (index != -1) {
721 SessionsListenerRecord record = mSessionsListeners.remove(index);
722 try {
723 record.mListener.asBinder().unlinkToDeath(record, 0);
724 } catch (Exception e) {
725 // ignore exceptions, the record is being removed
726 }
727 }
728 }
729 }
730
RoboErik8a2cfc32014-05-16 11:19:38 -0700731 /**
732 * Handles the dispatching of the media button events to one of the
733 * registered listeners, or if there was none, broadcast an
734 * ACTION_MEDIA_BUTTON intent to the rest of the system.
735 *
736 * @param keyEvent a non-null KeyEvent whose key code is one of the
737 * supported media buttons
738 * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held
739 * while this key event is dispatched.
740 */
741 @Override
742 public void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
743 if (keyEvent == null || !KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
744 Log.w(TAG, "Attempted to dispatch null or non-media key event.");
745 return;
746 }
Jeff Brown38d3feb2015-03-19 18:26:30 -0700747
RoboErik8a2cfc32014-05-16 11:19:38 -0700748 final int pid = Binder.getCallingPid();
749 final int uid = Binder.getCallingUid();
750 final long token = Binder.clearCallingIdentity();
RoboErik8a2cfc32014-05-16 11:19:38 -0700751 try {
Jeff Brown221a8272015-03-23 13:53:09 -0700752 if (DEBUG) {
753 Log.d(TAG, "dispatchMediaKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
754 + keyEvent);
755 }
Jeff Brown38d3feb2015-03-19 18:26:30 -0700756 if (!isUserSetupComplete()) {
757 // Global media key handling can have the side-effect of starting new
758 // activities which is undesirable while setup is in progress.
759 Slog.i(TAG, "Not dispatching media key event because user "
760 + "setup is in progress.");
761 return;
762 }
Jaewan Kimd409d182016-09-19 21:19:55 +0900763 if (isGlobalPriorityActive() && uid != Process.SYSTEM_UID) {
764 // Prevent dispatching key event through reflection while the global priority
765 // session is active.
766 Slog.i(TAG, "Only the system can dispatch media key event "
767 + "to the global priority session.");
768 return;
769 }
Jeff Brown38d3feb2015-03-19 18:26:30 -0700770
RoboErik8a2cfc32014-05-16 11:19:38 -0700771 synchronized (mLock) {
RoboErik870c5a62014-12-02 15:08:26 -0800772 // If we don't have a media button receiver to fall back on
773 // include non-playing sessions for dispatching
Jaewan Kim8f729082016-06-21 12:36:26 +0900774 boolean useNotPlayingSessions = true;
775 for (int userId : mCurrentUserIdList) {
776 UserRecord ur = mUserRecords.get(userId);
777 if (ur.mLastMediaButtonReceiver != null
778 || ur.mRestoredMediaButtonReceiver != null) {
779 useNotPlayingSessions = false;
780 break;
781 }
782 }
783
784 if (DEBUG) {
785 Log.d(TAG, "dispatchMediaKeyEvent, useNotPlayingSessions="
786 + useNotPlayingSessions);
787 }
788 MediaSessionRecord session = mPriorityStack.getDefaultMediaButtonSession(
789 mCurrentUserIdList, useNotPlayingSessions);
RoboErik9a9d0b52014-05-20 14:53:39 -0700790 if (isVoiceKey(keyEvent.getKeyCode())) {
791 handleVoiceKeyEventLocked(keyEvent, needWakeLock, session);
RoboErik8a2cfc32014-05-16 11:19:38 -0700792 } else {
RoboErik9a9d0b52014-05-20 14:53:39 -0700793 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, session);
RoboErik8a2cfc32014-05-16 11:19:38 -0700794 }
795 }
796 } finally {
797 Binder.restoreCallingIdentity(token);
798 }
799 }
800
RoboErika278ea72014-04-24 14:49:01 -0700801 @Override
RoboErik7c82ced2014-12-04 17:39:08 -0800802 public void dispatchAdjustVolume(int suggestedStream, int delta, int flags) {
RoboErikb69ffd42014-05-30 14:57:59 -0700803 final long token = Binder.clearCallingIdentity();
804 try {
805 synchronized (mLock) {
806 MediaSessionRecord session = mPriorityStack
Jaewan Kim8f729082016-06-21 12:36:26 +0900807 .getDefaultVolumeSession(mCurrentUserIdList);
RoboErik1ff5b162014-07-15 17:23:18 -0700808 dispatchAdjustVolumeLocked(suggestedStream, delta, flags, session);
RoboErikb69ffd42014-05-30 14:57:59 -0700809 }
810 } finally {
811 Binder.restoreCallingIdentity(token);
812 }
813 }
814
815 @Override
RoboErik19c95182014-06-23 15:38:48 -0700816 public void setRemoteVolumeController(IRemoteVolumeController rvc) {
817 final int pid = Binder.getCallingPid();
818 final int uid = Binder.getCallingUid();
819 final long token = Binder.clearCallingIdentity();
820 try {
John Spurlockeb69e242015-02-17 17:15:04 -0500821 enforceSystemUiPermission("listen for volume changes", pid, uid);
RoboErik19c95182014-06-23 15:38:48 -0700822 mRvc = rvc;
823 } finally {
824 Binder.restoreCallingIdentity(token);
825 }
826 }
827
828 @Override
RoboErikde9ba392014-09-26 12:51:01 -0700829 public boolean isGlobalPriorityActive() {
830 return mPriorityStack.isGlobalPriorityActive();
831 }
832
833 @Override
RoboErika278ea72014-04-24 14:49:01 -0700834 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
835 if (getContext().checkCallingOrSelfPermission(Manifest.permission.DUMP)
836 != PackageManager.PERMISSION_GRANTED) {
837 pw.println("Permission Denial: can't dump MediaSessionService from from pid="
838 + Binder.getCallingPid()
839 + ", uid=" + Binder.getCallingUid());
840 return;
841 }
842
843 pw.println("MEDIA SESSION SERVICE (dumpsys media_session)");
844 pw.println();
845
846 synchronized (mLock) {
RoboErika08adb242014-11-21 18:28:18 -0800847 pw.println(mSessionsListeners.size() + " sessions listeners.");
RoboErik4646d282014-05-13 10:13:04 -0700848 int count = mAllSessions.size();
RoboErika8f95142014-05-05 14:23:49 -0700849 pw.println(count + " Sessions:");
RoboErika278ea72014-04-24 14:49:01 -0700850 for (int i = 0; i < count; i++) {
RoboErik4646d282014-05-13 10:13:04 -0700851 mAllSessions.get(i).dump(pw, "");
RoboErika278ea72014-04-24 14:49:01 -0700852 pw.println();
RoboErika278ea72014-04-24 14:49:01 -0700853 }
RoboErika5b02322014-05-07 17:05:49 -0700854 mPriorityStack.dump(pw, "");
RoboErika8f95142014-05-05 14:23:49 -0700855
RoboErik4646d282014-05-13 10:13:04 -0700856 pw.println("User Records:");
857 count = mUserRecords.size();
RoboErika278ea72014-04-24 14:49:01 -0700858 for (int i = 0; i < count; i++) {
RoboErik7b3da2d2015-02-02 15:21:29 -0800859 UserRecord user = mUserRecords.get(mUserRecords.keyAt(i));
RoboErik4646d282014-05-13 10:13:04 -0700860 user.dumpLocked(pw, "");
RoboErika278ea72014-04-24 14:49:01 -0700861 }
862 }
863 }
RoboErik8a2cfc32014-05-16 11:19:38 -0700864
RoboErik2e7a9162014-06-04 16:53:45 -0700865 private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
866 final int uid) {
867 String packageName = null;
868 if (componentName != null) {
869 // If they gave us a component name verify they own the
870 // package
871 packageName = componentName.getPackageName();
872 enforcePackageName(packageName, uid);
873 }
874 // Check that they can make calls on behalf of the user and
875 // get the final user id
876 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
877 true /* allowAll */, true /* requireFull */, "getSessions", packageName);
878 // Check if they have the permissions or their component is
879 // enabled for the user they're calling from.
880 enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
881 return resolvedUserId;
882 }
883
RoboErik1ff5b162014-07-15 17:23:18 -0700884 private void dispatchAdjustVolumeLocked(int suggestedStream, int direction, int flags,
RoboErikb69ffd42014-05-30 14:57:59 -0700885 MediaSessionRecord session) {
RoboErik9c785402014-11-11 16:52:26 -0800886 boolean preferSuggestedStream = false;
887 if (isValidLocalStreamType(suggestedStream)
888 && AudioSystem.isStreamActive(suggestedStream, 0)) {
889 preferSuggestedStream = true;
890 }
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900891 if (DEBUG) {
892 Log.d(TAG, "Adjusting " + session + " by " + direction + ". flags="
893 + flags + ", suggestedStream=" + suggestedStream
894 + ", preferSuggestedStream=" + preferSuggestedStream);
895 }
RoboErik9c785402014-11-11 16:52:26 -0800896 if (session == null || preferSuggestedStream) {
RoboErik94c716e2014-09-14 13:54:31 -0700897 if ((flags & AudioManager.FLAG_ACTIVE_MEDIA_ONLY) != 0
898 && !AudioSystem.isStreamActive(AudioManager.STREAM_MUSIC, 0)) {
RoboErik3c45c292014-07-08 16:47:31 -0700899 if (DEBUG) {
900 Log.d(TAG, "No active session to adjust, skipping media only volume event");
RoboErik3c45c292014-07-08 16:47:31 -0700901 }
RoboErikb7c014c2014-07-22 15:58:22 -0700902 return;
RoboErik3c45c292014-07-08 16:47:31 -0700903 }
Shibin George19e84042016-06-14 20:42:13 +0530904
905 // Execute mAudioService.adjustSuggestedStreamVolume() on
906 // handler thread of MediaSessionService.
907 // This will release the MediaSessionService.mLock sooner and avoid
908 // a potential deadlock between MediaSessionService.mLock and
909 // ActivityManagerService lock.
910 mHandler.post(new Runnable() {
911 @Override
912 public void run() {
913 try {
914 String packageName = getContext().getOpPackageName();
915 mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
916 flags, packageName, TAG);
917 } catch (RemoteException e) {
918 Log.e(TAG, "Error adjusting default volume.", e);
919 }
920 }
921 });
RoboErikb69ffd42014-05-30 14:57:59 -0700922 } else {
RoboErik0dac35a2014-08-12 15:48:49 -0700923 session.adjustVolume(direction, flags, getContext().getPackageName(),
Jaewan Kim8f729082016-06-21 12:36:26 +0900924 Process.SYSTEM_UID, true);
RoboErikb69ffd42014-05-30 14:57:59 -0700925 }
926 }
927
RoboErik9a9d0b52014-05-20 14:53:39 -0700928 private void handleVoiceKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock,
929 MediaSessionRecord session) {
930 if (session != null && session.hasFlag(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY)) {
931 // If the phone app has priority just give it the event
932 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, session);
933 return;
934 }
935 int action = keyEvent.getAction();
936 boolean isLongPress = (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0;
937 if (action == KeyEvent.ACTION_DOWN) {
938 if (keyEvent.getRepeatCount() == 0) {
939 mVoiceButtonDown = true;
940 mVoiceButtonHandled = false;
941 } else if (mVoiceButtonDown && !mVoiceButtonHandled && isLongPress) {
942 mVoiceButtonHandled = true;
943 startVoiceInput(needWakeLock);
944 }
945 } else if (action == KeyEvent.ACTION_UP) {
946 if (mVoiceButtonDown) {
947 mVoiceButtonDown = false;
948 if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
949 // Resend the down then send this event through
950 KeyEvent downEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_DOWN);
951 dispatchMediaKeyEventLocked(downEvent, needWakeLock, session);
952 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, session);
953 }
954 }
955 }
956 }
957
958 private void dispatchMediaKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock,
959 MediaSessionRecord session) {
960 if (session != null) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900961 if (DEBUG_MEDIA_KEY_EVENT) {
962 Log.d(TAG, "Sending " + keyEvent + " to " + session);
RoboErik9a9d0b52014-05-20 14:53:39 -0700963 }
964 if (needWakeLock) {
965 mKeyEventReceiver.aquireWakeLockLocked();
966 }
967 // If we don't need a wakelock use -1 as the id so we
968 // won't release it later
969 session.sendMediaButton(keyEvent,
970 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
Jaewan Kim8f729082016-06-21 12:36:26 +0900971 mKeyEventReceiver, Process.SYSTEM_UID,
Donghyun Cho1ea56832016-02-23 16:30:07 +0900972 getContext().getPackageName());
RoboErik9a9d0b52014-05-20 14:53:39 -0700973 } else {
RoboErikb214efb2014-07-24 13:20:30 -0700974 // Launch the last PendingIntent we had with priority
Jaewan Kim8f729082016-06-21 12:36:26 +0900975 for (int userId : mCurrentUserIdList) {
976 UserRecord user = mUserRecords.get(userId);
977 if (user.mLastMediaButtonReceiver == null
978 && user.mRestoredMediaButtonReceiver == null) {
979 continue;
980 }
RoboErikb214efb2014-07-24 13:20:30 -0700981 if (needWakeLock) {
982 mKeyEventReceiver.aquireWakeLockLocked();
983 }
984 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
Insun Kang2054db32016-04-07 15:34:34 +0900985 mediaButtonIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
RoboErikb214efb2014-07-24 13:20:30 -0700986 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
987 try {
RoboErikc8f92d12015-01-05 16:48:07 -0800988 if (user.mLastMediaButtonReceiver != null) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900989 if (DEBUG_MEDIA_KEY_EVENT) {
990 Log.d(TAG, "Sending " + keyEvent
991 + " to the last known pendingIntent "
992 + user.mLastMediaButtonReceiver);
993 }
RoboErikc8f92d12015-01-05 16:48:07 -0800994 user.mLastMediaButtonReceiver.send(getContext(),
995 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
riddle_hsu02ed0122015-10-20 16:00:15 +0800996 mediaButtonIntent, mKeyEventReceiver, mHandler);
RoboErikc8f92d12015-01-05 16:48:07 -0800997 } else {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900998 if (DEBUG_MEDIA_KEY_EVENT) {
999 Log.d(TAG, "Sending " + keyEvent + " to the restored intent "
1000 + user.mRestoredMediaButtonReceiver);
1001 }
RoboErikc8f92d12015-01-05 16:48:07 -08001002 mediaButtonIntent.setComponent(user.mRestoredMediaButtonReceiver);
1003 getContext().sendBroadcastAsUser(mediaButtonIntent,
Jaewan Kim8f729082016-06-21 12:36:26 +09001004 UserHandle.of(userId));
RoboErikc8f92d12015-01-05 16:48:07 -08001005 }
RoboErikb214efb2014-07-24 13:20:30 -07001006 } catch (CanceledException e) {
1007 Log.i(TAG, "Error sending key event to media button receiver "
1008 + user.mLastMediaButtonReceiver, e);
1009 }
Jaewan Kim8f729082016-06-21 12:36:26 +09001010 return;
RoboErik9a9d0b52014-05-20 14:53:39 -07001011 }
Jaewan Kim8f729082016-06-21 12:36:26 +09001012 if (DEBUG) {
1013 Log.d(TAG, "Sending media key ordered broadcast");
1014 }
1015 if (needWakeLock) {
1016 mMediaEventWakeLock.acquire();
1017 }
1018 // Fallback to legacy behavior
1019 Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
1020 keyIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1021 keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
1022 if (needWakeLock) {
1023 keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
1024 }
1025 // Send broadcast only to the full user.
1026 getContext().sendOrderedBroadcastAsUser(keyIntent, UserHandle.CURRENT,
1027 null, mKeyEventDone, mHandler, Activity.RESULT_OK, null, null);
RoboErik9a9d0b52014-05-20 14:53:39 -07001028 }
1029 }
1030
1031 private void startVoiceInput(boolean needWakeLock) {
1032 Intent voiceIntent = null;
1033 // select which type of search to launch:
1034 // - screen on and device unlocked: action is ACTION_WEB_SEARCH
1035 // - device locked or screen off: action is
1036 // ACTION_VOICE_SEARCH_HANDS_FREE
1037 // with EXTRA_SECURE set to true if the device is securely locked
1038 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1039 boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
1040 if (!isLocked && pm.isScreenOn()) {
1041 voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
1042 Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
1043 } else {
1044 voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
1045 voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
1046 isLocked && mKeyguardManager.isKeyguardSecure());
1047 Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
1048 }
1049 // start the search activity
1050 if (needWakeLock) {
1051 mMediaEventWakeLock.acquire();
1052 }
1053 try {
1054 if (voiceIntent != null) {
1055 voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1056 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Jaewan Kim8f729082016-06-21 12:36:26 +09001057 if (DEBUG) Log.d(TAG, "voiceIntent: " + voiceIntent);
RoboErik9a9d0b52014-05-20 14:53:39 -07001058 getContext().startActivityAsUser(voiceIntent, UserHandle.CURRENT);
1059 }
1060 } catch (ActivityNotFoundException e) {
1061 Log.w(TAG, "No activity for search: " + e);
1062 } finally {
1063 if (needWakeLock) {
1064 mMediaEventWakeLock.release();
1065 }
1066 }
1067 }
1068
1069 private boolean isVoiceKey(int keyCode) {
1070 return keyCode == KeyEvent.KEYCODE_HEADSETHOOK;
1071 }
1072
Jeff Brown38d3feb2015-03-19 18:26:30 -07001073 private boolean isUserSetupComplete() {
1074 return Settings.Secure.getIntForUser(getContext().getContentResolver(),
1075 Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1076 }
1077
RoboErik9c785402014-11-11 16:52:26 -08001078 // we only handle public stream types, which are 0-5
1079 private boolean isValidLocalStreamType(int streamType) {
1080 return streamType >= AudioManager.STREAM_VOICE_CALL
1081 && streamType <= AudioManager.STREAM_NOTIFICATION;
1082 }
1083
RoboErik418c10c2014-05-19 09:25:25 -07001084 private KeyEventWakeLockReceiver mKeyEventReceiver = new KeyEventWakeLockReceiver(mHandler);
1085
RoboErikb214efb2014-07-24 13:20:30 -07001086 class KeyEventWakeLockReceiver extends ResultReceiver implements Runnable,
1087 PendingIntent.OnFinished {
RoboErik418c10c2014-05-19 09:25:25 -07001088 private final Handler mHandler;
1089 private int mRefCount = 0;
1090 private int mLastTimeoutId = 0;
1091
1092 public KeyEventWakeLockReceiver(Handler handler) {
1093 super(handler);
1094 mHandler = handler;
1095 }
1096
1097 public void onTimeout() {
1098 synchronized (mLock) {
1099 if (mRefCount == 0) {
1100 // We've already released it, so just return
1101 return;
1102 }
1103 mLastTimeoutId++;
1104 mRefCount = 0;
1105 releaseWakeLockLocked();
1106 }
1107 }
1108
1109 public void aquireWakeLockLocked() {
1110 if (mRefCount == 0) {
1111 mMediaEventWakeLock.acquire();
1112 }
1113 mRefCount++;
1114 mHandler.removeCallbacks(this);
1115 mHandler.postDelayed(this, WAKELOCK_TIMEOUT);
1116
1117 }
1118
1119 @Override
1120 public void run() {
1121 onTimeout();
1122 }
1123
RoboErik8a2cfc32014-05-16 11:19:38 -07001124 @Override
1125 protected void onReceiveResult(int resultCode, Bundle resultData) {
RoboErik418c10c2014-05-19 09:25:25 -07001126 if (resultCode < mLastTimeoutId) {
1127 // Ignore results from calls that were before the last
1128 // timeout, just in case.
1129 return;
1130 } else {
1131 synchronized (mLock) {
1132 if (mRefCount > 0) {
1133 mRefCount--;
1134 if (mRefCount == 0) {
1135 releaseWakeLockLocked();
1136 }
1137 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001138 }
1139 }
1140 }
RoboErik418c10c2014-05-19 09:25:25 -07001141
1142 private void releaseWakeLockLocked() {
1143 mMediaEventWakeLock.release();
1144 mHandler.removeCallbacks(this);
1145 }
RoboErikb214efb2014-07-24 13:20:30 -07001146
1147 @Override
1148 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
1149 String resultData, Bundle resultExtras) {
1150 onReceiveResult(resultCode, null);
1151 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001152 };
1153
1154 BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
1155 @Override
1156 public void onReceive(Context context, Intent intent) {
1157 if (intent == null) {
1158 return;
1159 }
1160 Bundle extras = intent.getExtras();
1161 if (extras == null) {
1162 return;
1163 }
1164 synchronized (mLock) {
1165 if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)
1166 && mMediaEventWakeLock.isHeld()) {
1167 mMediaEventWakeLock.release();
1168 }
1169 }
1170 }
1171 };
RoboErik01fe6612014-02-13 14:19:04 -08001172 }
1173
RoboErik2e7a9162014-06-04 16:53:45 -07001174 final class MessageHandler extends Handler {
1175 private static final int MSG_SESSIONS_CHANGED = 1;
1176
1177 @Override
1178 public void handleMessage(Message msg) {
1179 switch (msg.what) {
1180 case MSG_SESSIONS_CHANGED:
1181 pushSessionsChanged(msg.arg1);
1182 break;
1183 }
1184 }
1185
1186 public void post(int what, int arg1, int arg2) {
1187 obtainMessage(what, arg1, arg2).sendToTarget();
1188 }
1189 }
RoboErik01fe6612014-02-13 14:19:04 -08001190}