blob: a5efc8396b200a7d6a14437556ac59b66ec3b4ee [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;
RoboErikd2b8c942014-08-19 11:23:40 -070042import android.media.session.MediaController.PlaybackInfo;
Jeff Browndba34ba2014-06-24 20:46:03 -070043import android.media.session.MediaSession;
RoboErik7c82ced2014-12-04 17:39:08 -080044import android.media.session.MediaSessionManager;
RoboErik7aef77b2014-08-08 15:56:54 -070045import android.net.Uri;
RoboErik01fe6612014-02-13 14:19:04 -080046import android.os.Binder;
RoboErik8a2cfc32014-05-16 11:19:38 -070047import android.os.Bundle;
RoboErik8ae0f342014-02-24 18:02:08 -080048import android.os.Handler;
RoboErike7880d82014-04-30 12:48:25 -070049import android.os.IBinder;
RoboErik2e7a9162014-06-04 16:53:45 -070050import android.os.Message;
RoboErik8a2cfc32014-05-16 11:19:38 -070051import android.os.PowerManager;
RoboErik01fe6612014-02-13 14:19:04 -080052import android.os.RemoteException;
RoboErik8a2cfc32014-05-16 11:19:38 -070053import android.os.ResultReceiver;
RoboErikb69ffd42014-05-30 14:57:59 -070054import android.os.ServiceManager;
RoboErike7880d82014-04-30 12:48:25 -070055import android.os.UserHandle;
56import 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;
RoboErik4646d282014-05-13 10:13:04 -070060import android.util.SparseArray;
RoboErik8a2cfc32014-05-16 11:19:38 -070061import android.view.KeyEvent;
RoboErik01fe6612014-02-13 14:19:04 -080062
John Spurlockeb69e242015-02-17 17:15:04 -050063import com.android.server.LocalServices;
RoboErik01fe6612014-02-13 14:19:04 -080064import com.android.server.SystemService;
RoboErika278ea72014-04-24 14:49:01 -070065import com.android.server.Watchdog;
66import com.android.server.Watchdog.Monitor;
RoboErik01fe6612014-02-13 14:19:04 -080067
RoboErika278ea72014-04-24 14:49:01 -070068import java.io.FileDescriptor;
69import java.io.PrintWriter;
RoboErik01fe6612014-02-13 14:19:04 -080070import java.util.ArrayList;
RoboErike7880d82014-04-30 12:48:25 -070071import java.util.List;
RoboErik01fe6612014-02-13 14:19:04 -080072
73/**
74 * System implementation of MediaSessionManager
75 */
RoboErika278ea72014-04-24 14:49:01 -070076public class MediaSessionService extends SystemService implements Monitor {
RoboErik01fe6612014-02-13 14:19:04 -080077 private static final String TAG = "MediaSessionService";
78 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
79
RoboErik418c10c2014-05-19 09:25:25 -070080 private static final int WAKELOCK_TIMEOUT = 5000;
81
RoboErik2610d712015-01-07 11:10:23 -080082 /* package */final IBinder mICallback = new Binder();
83
RoboErik01fe6612014-02-13 14:19:04 -080084 private final SessionManagerImpl mSessionManagerImpl;
RoboErika8f95142014-05-05 14:23:49 -070085 private final MediaSessionStack mPriorityStack;
RoboErik01fe6612014-02-13 14:19:04 -080086
RoboErik4646d282014-05-13 10:13:04 -070087 private final ArrayList<MediaSessionRecord> mAllSessions = new ArrayList<MediaSessionRecord>();
88 private final SparseArray<UserRecord> mUserRecords = new SparseArray<UserRecord>();
RoboErik2e7a9162014-06-04 16:53:45 -070089 private final ArrayList<SessionsListenerRecord> mSessionsListeners
90 = new ArrayList<SessionsListenerRecord>();
RoboErik01fe6612014-02-13 14:19:04 -080091 private final Object mLock = new Object();
RoboErik2e7a9162014-06-04 16:53:45 -070092 private final MessageHandler mHandler = new MessageHandler();
RoboErik8a2cfc32014-05-16 11:19:38 -070093 private final PowerManager.WakeLock mMediaEventWakeLock;
RoboErik519c7742014-11-18 10:59:09 -080094 private final boolean mUseMasterVolume;
RoboErik01fe6612014-02-13 14:19:04 -080095
RoboErik9a9d0b52014-05-20 14:53:39 -070096 private KeyguardManager mKeyguardManager;
RoboErikb69ffd42014-05-30 14:57:59 -070097 private IAudioService mAudioService;
RoboErik2610d712015-01-07 11:10:23 -080098 private AudioManager mAudioManager;
John Spurlockeb69e242015-02-17 17:15:04 -050099 private AudioManagerInternal mAudioManagerInternal;
RoboErik6f0e4dd2014-06-17 16:56:27 -0700100 private ContentResolver mContentResolver;
RoboErik7aef77b2014-08-08 15:56:54 -0700101 private SettingsObserver mSettingsObserver;
RoboErik9a9d0b52014-05-20 14:53:39 -0700102
RoboErik4646d282014-05-13 10:13:04 -0700103 private int mCurrentUserId = -1;
RoboErike7880d82014-04-30 12:48:25 -0700104
RoboErik19c95182014-06-23 15:38:48 -0700105 // Used to notify system UI when remote volume was changed. TODO find a
106 // better way to handle this.
107 private IRemoteVolumeController mRvc;
108
RoboErik01fe6612014-02-13 14:19:04 -0800109 public MediaSessionService(Context context) {
110 super(context);
111 mSessionManagerImpl = new SessionManagerImpl();
RoboErika8f95142014-05-05 14:23:49 -0700112 mPriorityStack = new MediaSessionStack();
RoboErik8a2cfc32014-05-16 11:19:38 -0700113 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
114 mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
RoboErik519c7742014-11-18 10:59:09 -0800115 mUseMasterVolume = context.getResources().getBoolean(
116 com.android.internal.R.bool.config_useMasterVolume);
RoboErik01fe6612014-02-13 14:19:04 -0800117 }
118
119 @Override
120 public void onStart() {
121 publishBinderService(Context.MEDIA_SESSION_SERVICE, mSessionManagerImpl);
RoboErika278ea72014-04-24 14:49:01 -0700122 Watchdog.getInstance().addMonitor(this);
RoboErik9a9d0b52014-05-20 14:53:39 -0700123 mKeyguardManager =
124 (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
RoboErikb69ffd42014-05-30 14:57:59 -0700125 mAudioService = getAudioService();
RoboErik2610d712015-01-07 11:10:23 -0800126 mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
John Spurlockeb69e242015-02-17 17:15:04 -0500127 mAudioManagerInternal = LocalServices.getService(AudioManagerInternal.class);
RoboErik6f0e4dd2014-06-17 16:56:27 -0700128 mContentResolver = getContext().getContentResolver();
RoboErik7aef77b2014-08-08 15:56:54 -0700129 mSettingsObserver = new SettingsObserver();
130 mSettingsObserver.observe();
RoboErikc8f92d12015-01-05 16:48:07 -0800131
132 updateUser();
RoboErikb69ffd42014-05-30 14:57:59 -0700133 }
134
135 private IAudioService getAudioService() {
136 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
137 return IAudioService.Stub.asInterface(b);
RoboErik07c70772014-03-20 13:33:52 -0700138 }
139
RoboErika8f95142014-05-05 14:23:49 -0700140 public void updateSession(MediaSessionRecord record) {
RoboErike7880d82014-04-30 12:48:25 -0700141 synchronized (mLock) {
RoboErik4646d282014-05-13 10:13:04 -0700142 if (!mAllSessions.contains(record)) {
143 Log.d(TAG, "Unknown session updated. Ignoring.");
144 return;
145 }
RoboErika8f95142014-05-05 14:23:49 -0700146 mPriorityStack.onSessionStateChange(record);
RoboErike7880d82014-04-30 12:48:25 -0700147 }
RoboErik2e7a9162014-06-04 16:53:45 -0700148 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, record.getUserId(), 0);
RoboErike7880d82014-04-30 12:48:25 -0700149 }
150
RoboErik9c5b7cb2015-01-15 15:09:09 -0800151 /**
152 * Tells the system UI that volume has changed on a remote session.
153 */
154 public void notifyRemoteVolumeChanged(int flags, MediaSessionRecord session) {
155 if (mRvc == null) {
156 return;
157 }
158 try {
159 mRvc.remoteVolumeChanged(session.getControllerBinder(), flags);
160 } catch (Exception e) {
161 Log.wtf(TAG, "Error sending volume change to system UI.", e);
162 }
163 }
164
RoboErika8f95142014-05-05 14:23:49 -0700165 public void onSessionPlaystateChange(MediaSessionRecord record, int oldState, int newState) {
RoboErik2e7a9162014-06-04 16:53:45 -0700166 boolean updateSessions = false;
RoboErika8f95142014-05-05 14:23:49 -0700167 synchronized (mLock) {
RoboErik4646d282014-05-13 10:13:04 -0700168 if (!mAllSessions.contains(record)) {
169 Log.d(TAG, "Unknown session changed playback state. Ignoring.");
170 return;
171 }
RoboErik2e7a9162014-06-04 16:53:45 -0700172 updateSessions = mPriorityStack.onPlaystateChange(record, oldState, newState);
173 }
174 if (updateSessions) {
175 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, record.getUserId(), 0);
RoboErika8f95142014-05-05 14:23:49 -0700176 }
177 }
178
RoboErik19c95182014-06-23 15:38:48 -0700179 public void onSessionPlaybackTypeChanged(MediaSessionRecord record) {
180 synchronized (mLock) {
181 if (!mAllSessions.contains(record)) {
182 Log.d(TAG, "Unknown session changed playback type. Ignoring.");
183 return;
184 }
185 pushRemoteVolumeUpdateLocked(record.getUserId());
186 }
187 }
188
RoboErika278ea72014-04-24 14:49:01 -0700189 @Override
RoboErik4646d282014-05-13 10:13:04 -0700190 public void onStartUser(int userHandle) {
191 updateUser();
192 }
193
194 @Override
195 public void onSwitchUser(int userHandle) {
196 updateUser();
197 }
198
199 @Override
200 public void onStopUser(int userHandle) {
201 synchronized (mLock) {
202 UserRecord user = mUserRecords.get(userHandle);
203 if (user != null) {
204 destroyUserLocked(user);
205 }
206 }
207 }
208
209 @Override
RoboErika278ea72014-04-24 14:49:01 -0700210 public void monitor() {
211 synchronized (mLock) {
212 // Check for deadlock
213 }
214 }
215
RoboErik4646d282014-05-13 10:13:04 -0700216 protected void enforcePhoneStatePermission(int pid, int uid) {
217 if (getContext().checkPermission(android.Manifest.permission.MODIFY_PHONE_STATE, pid, uid)
218 != PackageManager.PERMISSION_GRANTED) {
219 throw new SecurityException("Must hold the MODIFY_PHONE_STATE permission.");
220 }
221 }
222
RoboErik01fe6612014-02-13 14:19:04 -0800223 void sessionDied(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700224 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800225 destroySessionLocked(session);
226 }
227 }
228
229 void destroySession(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700230 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800231 destroySessionLocked(session);
232 }
233 }
234
RoboErik4646d282014-05-13 10:13:04 -0700235 private void updateUser() {
236 synchronized (mLock) {
237 int userId = ActivityManager.getCurrentUser();
238 if (mCurrentUserId != userId) {
239 final int oldUserId = mCurrentUserId;
240 mCurrentUserId = userId; // do this first
241
242 UserRecord oldUser = mUserRecords.get(oldUserId);
243 if (oldUser != null) {
244 oldUser.stopLocked();
245 }
246
247 UserRecord newUser = getOrCreateUser(userId);
248 newUser.startLocked();
249 }
250 }
251 }
252
RoboErik7aef77b2014-08-08 15:56:54 -0700253 private void updateActiveSessionListeners() {
254 synchronized (mLock) {
255 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
256 SessionsListenerRecord listener = mSessionsListeners.get(i);
257 try {
258 enforceMediaPermissions(listener.mComponentName, listener.mPid, listener.mUid,
259 listener.mUserId);
260 } catch (SecurityException e) {
261 Log.i(TAG, "ActiveSessionsListener " + listener.mComponentName
262 + " is no longer authorized. Disconnecting.");
263 mSessionsListeners.remove(i);
264 try {
265 listener.mListener
266 .onActiveSessionsChanged(new ArrayList<MediaSession.Token>());
267 } catch (Exception e1) {
268 // ignore
269 }
270 }
271 }
272 }
273 }
274
RoboErik4646d282014-05-13 10:13:04 -0700275 /**
276 * Stop the user and unbind from everything.
277 *
278 * @param user The user to dispose of
279 */
280 private void destroyUserLocked(UserRecord user) {
281 user.stopLocked();
282 user.destroyLocked();
283 mUserRecords.remove(user.mUserId);
284 }
285
286 /*
287 * When a session is removed several things need to happen.
288 * 1. We need to remove it from the relevant user.
289 * 2. We need to remove it from the priority stack.
290 * 3. We need to remove it from all sessions.
291 * 4. If this is the system priority session we need to clear it.
292 * 5. We need to unlink to death from the cb binder
293 * 6. We need to tell the session to do any final cleanup (onDestroy)
294 */
RoboErik01fe6612014-02-13 14:19:04 -0800295 private void destroySessionLocked(MediaSessionRecord session) {
RoboErik4646d282014-05-13 10:13:04 -0700296 int userId = session.getUserId();
297 UserRecord user = mUserRecords.get(userId);
298 if (user != null) {
299 user.removeSessionLocked(session);
300 }
301
RoboErika8f95142014-05-05 14:23:49 -0700302 mPriorityStack.removeSession(session);
RoboErik4646d282014-05-13 10:13:04 -0700303 mAllSessions.remove(session);
RoboErik4646d282014-05-13 10:13:04 -0700304
305 try {
306 session.getCallback().asBinder().unlinkToDeath(session, 0);
307 } catch (Exception e) {
308 // ignore exceptions while destroying a session.
309 }
310 session.onDestroy();
RoboErik2e7a9162014-06-04 16:53:45 -0700311
312 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, session.getUserId(), 0);
RoboErik01fe6612014-02-13 14:19:04 -0800313 }
314
315 private void enforcePackageName(String packageName, int uid) {
316 if (TextUtils.isEmpty(packageName)) {
317 throw new IllegalArgumentException("packageName may not be empty");
318 }
319 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
320 final int packageCount = packages.length;
321 for (int i = 0; i < packageCount; i++) {
322 if (packageName.equals(packages[i])) {
323 return;
324 }
325 }
326 throw new IllegalArgumentException("packageName is not owned by the calling process");
327 }
328
RoboErike7880d82014-04-30 12:48:25 -0700329 /**
330 * Checks a caller's authorization to register an IRemoteControlDisplay.
331 * Authorization is granted if one of the following is true:
332 * <ul>
333 * <li>the caller has android.Manifest.permission.MEDIA_CONTENT_CONTROL
334 * permission</li>
RoboErika5b02322014-05-07 17:05:49 -0700335 * <li>the caller's listener is one of the enabled notification listeners
336 * for the caller's user</li>
RoboErike7880d82014-04-30 12:48:25 -0700337 * </ul>
338 */
RoboErika5b02322014-05-07 17:05:49 -0700339 private void enforceMediaPermissions(ComponentName compName, int pid, int uid,
340 int resolvedUserId) {
John Spurlockbe19ed02015-02-22 10:57:55 -0500341 if (isCurrentVolumeController(uid)) return;
RoboErike7880d82014-04-30 12:48:25 -0700342 if (getContext()
343 .checkPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
344 != PackageManager.PERMISSION_GRANTED
RoboErika5b02322014-05-07 17:05:49 -0700345 && !isEnabledNotificationListener(compName, UserHandle.getUserId(uid),
346 resolvedUserId)) {
RoboErike7880d82014-04-30 12:48:25 -0700347 throw new SecurityException("Missing permission to control media.");
348 }
349 }
350
John Spurlockbe19ed02015-02-22 10:57:55 -0500351 private boolean isCurrentVolumeController(int uid) {
John Spurlockeb69e242015-02-17 17:15:04 -0500352 if (mAudioManagerInternal != null) {
353 final int vcuid = mAudioManagerInternal.getVolumeControllerUid();
354 if (vcuid > 0 && uid == vcuid) {
John Spurlockbe19ed02015-02-22 10:57:55 -0500355 return true;
John Spurlockeb69e242015-02-17 17:15:04 -0500356 }
357 }
John Spurlockbe19ed02015-02-22 10:57:55 -0500358 return false;
359 }
360
361 private void enforceSystemUiPermission(String action, int pid, int uid) {
362 if (isCurrentVolumeController(uid)) return;
RoboErik19c95182014-06-23 15:38:48 -0700363 if (getContext().checkPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
364 pid, uid) != PackageManager.PERMISSION_GRANTED) {
365 throw new SecurityException("Only system ui may " + action);
366 }
367 }
368
RoboErika5b02322014-05-07 17:05:49 -0700369 /**
370 * This checks if the component is an enabled notification listener for the
371 * specified user. Enabled components may only operate on behalf of the user
372 * they're running as.
373 *
374 * @param compName The component that is enabled.
375 * @param userId The user id of the caller.
376 * @param forUserId The user id they're making the request on behalf of.
377 * @return True if the component is enabled, false otherwise
378 */
379 private boolean isEnabledNotificationListener(ComponentName compName, int userId,
380 int forUserId) {
381 if (userId != forUserId) {
382 // You may not access another user's content as an enabled listener.
383 return false;
384 }
RoboErik51fa6bc2014-06-20 14:59:58 -0700385 if (DEBUG) {
386 Log.d(TAG, "Checking if enabled notification listener " + compName);
387 }
RoboErike7880d82014-04-30 12:48:25 -0700388 if (compName != null) {
RoboErik6f0e4dd2014-06-17 16:56:27 -0700389 final String enabledNotifListeners = Settings.Secure.getStringForUser(mContentResolver,
RoboErike7880d82014-04-30 12:48:25 -0700390 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
RoboErika5b02322014-05-07 17:05:49 -0700391 userId);
RoboErike7880d82014-04-30 12:48:25 -0700392 if (enabledNotifListeners != null) {
393 final String[] components = enabledNotifListeners.split(":");
394 for (int i = 0; i < components.length; i++) {
395 final ComponentName component =
396 ComponentName.unflattenFromString(components[i]);
397 if (component != null) {
398 if (compName.equals(component)) {
399 if (DEBUG) {
400 Log.d(TAG, "ok to get sessions: " + component +
401 " is authorized notification listener");
402 }
403 return true;
404 }
405 }
406 }
407 }
408 if (DEBUG) {
409 Log.d(TAG, "not ok to get sessions, " + compName +
RoboErika5b02322014-05-07 17:05:49 -0700410 " is not in list of ENABLED_NOTIFICATION_LISTENERS for user " + userId);
RoboErike7880d82014-04-30 12:48:25 -0700411 }
412 }
413 return false;
414 }
415
RoboErika5b02322014-05-07 17:05:49 -0700416 private MediaSessionRecord createSessionInternal(int callerPid, int callerUid, int userId,
RoboErik4646d282014-05-13 10:13:04 -0700417 String callerPackageName, ISessionCallback cb, String tag) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800418 synchronized (mLock) {
RoboErika5b02322014-05-07 17:05:49 -0700419 return createSessionLocked(callerPid, callerUid, userId, callerPackageName, cb, tag);
RoboErik01fe6612014-02-13 14:19:04 -0800420 }
421 }
422
RoboErik4646d282014-05-13 10:13:04 -0700423 /*
424 * When a session is created the following things need to happen.
RoboErik8a2cfc32014-05-16 11:19:38 -0700425 * 1. Its callback binder needs a link to death
RoboErik4646d282014-05-13 10:13:04 -0700426 * 2. It needs to be added to all sessions.
427 * 3. It needs to be added to the priority stack.
428 * 4. It needs to be added to the relevant user record.
429 */
RoboErika5b02322014-05-07 17:05:49 -0700430 private MediaSessionRecord createSessionLocked(int callerPid, int callerUid, int userId,
431 String callerPackageName, ISessionCallback cb, String tag) {
RoboErik4646d282014-05-13 10:13:04 -0700432
RoboErika5b02322014-05-07 17:05:49 -0700433 final MediaSessionRecord session = new MediaSessionRecord(callerPid, callerUid, userId,
434 callerPackageName, cb, tag, this, mHandler);
RoboErik01fe6612014-02-13 14:19:04 -0800435 try {
436 cb.asBinder().linkToDeath(session, 0);
437 } catch (RemoteException e) {
438 throw new RuntimeException("Media Session owner died prematurely.", e);
439 }
RoboErik4646d282014-05-13 10:13:04 -0700440
441 mAllSessions.add(session);
RoboErika8f95142014-05-05 14:23:49 -0700442 mPriorityStack.addSession(session);
RoboErik4646d282014-05-13 10:13:04 -0700443
444 UserRecord user = getOrCreateUser(userId);
445 user.addSessionLocked(session);
446
RoboErik2e7a9162014-06-04 16:53:45 -0700447 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, userId, 0);
448
RoboErik01fe6612014-02-13 14:19:04 -0800449 if (DEBUG) {
RoboErika5b02322014-05-07 17:05:49 -0700450 Log.d(TAG, "Created session for package " + callerPackageName + " with tag " + tag);
RoboErik01fe6612014-02-13 14:19:04 -0800451 }
452 return session;
453 }
454
RoboErik4646d282014-05-13 10:13:04 -0700455 private UserRecord getOrCreateUser(int userId) {
456 UserRecord user = mUserRecords.get(userId);
457 if (user == null) {
458 user = new UserRecord(getContext(), userId);
459 mUserRecords.put(userId, user);
460 }
461 return user;
462 }
463
RoboErik2e7a9162014-06-04 16:53:45 -0700464 private int findIndexOfSessionsListenerLocked(IActiveSessionsListener listener) {
465 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
RoboErika08adb242014-11-21 18:28:18 -0800466 if (mSessionsListeners.get(i).mListener.asBinder() == listener.asBinder()) {
RoboErik2e7a9162014-06-04 16:53:45 -0700467 return i;
468 }
469 }
470 return -1;
471 }
472
RoboErike7880d82014-04-30 12:48:25 -0700473 private boolean isSessionDiscoverable(MediaSessionRecord record) {
RoboErik4646d282014-05-13 10:13:04 -0700474 // TODO probably want to check more than if it's active.
RoboErika8f95142014-05-05 14:23:49 -0700475 return record.isActive();
RoboErike7880d82014-04-30 12:48:25 -0700476 }
477
RoboErik2e7a9162014-06-04 16:53:45 -0700478 private void pushSessionsChanged(int userId) {
479 synchronized (mLock) {
480 List<MediaSessionRecord> records = mPriorityStack.getActiveSessions(userId);
481 int size = records.size();
RoboErik870c5a62014-12-02 15:08:26 -0800482 if (size > 0 && records.get(0).isPlaybackActive(false)) {
RoboErikb214efb2014-07-24 13:20:30 -0700483 rememberMediaButtonReceiverLocked(records.get(0));
RoboErik6f0e4dd2014-06-17 16:56:27 -0700484 }
Jeff Browndba34ba2014-06-24 20:46:03 -0700485 ArrayList<MediaSession.Token> tokens = new ArrayList<MediaSession.Token>();
RoboErik2e7a9162014-06-04 16:53:45 -0700486 for (int i = 0; i < size; i++) {
Jeff Browndba34ba2014-06-24 20:46:03 -0700487 tokens.add(new MediaSession.Token(records.get(i).getControllerBinder()));
RoboErik2e7a9162014-06-04 16:53:45 -0700488 }
RoboErik19c95182014-06-23 15:38:48 -0700489 pushRemoteVolumeUpdateLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700490 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
491 SessionsListenerRecord record = mSessionsListeners.get(i);
492 if (record.mUserId == UserHandle.USER_ALL || record.mUserId == userId) {
493 try {
494 record.mListener.onActiveSessionsChanged(tokens);
495 } catch (RemoteException e) {
496 Log.w(TAG, "Dead ActiveSessionsListener in pushSessionsChanged, removing",
497 e);
498 mSessionsListeners.remove(i);
499 }
500 }
501 }
502 }
503 }
504
RoboErik19c95182014-06-23 15:38:48 -0700505 private void pushRemoteVolumeUpdateLocked(int userId) {
506 if (mRvc != null) {
507 try {
508 MediaSessionRecord record = mPriorityStack.getDefaultRemoteSession(userId);
509 mRvc.updateRemoteController(record == null ? null : record.getControllerBinder());
510 } catch (RemoteException e) {
511 Log.wtf(TAG, "Error sending default remote volume to sys ui.", e);
512 }
513 }
514 }
515
RoboErikb214efb2014-07-24 13:20:30 -0700516 private void rememberMediaButtonReceiverLocked(MediaSessionRecord record) {
517 PendingIntent receiver = record.getMediaButtonReceiver();
518 UserRecord user = mUserRecords.get(record.getUserId());
519 if (receiver != null && user != null) {
520 user.mLastMediaButtonReceiver = receiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800521 ComponentName component = receiver.getIntent().getComponent();
522 if (component != null && record.getPackageName().equals(component.getPackageName())) {
523 Settings.Secure.putStringForUser(mContentResolver,
524 Settings.System.MEDIA_BUTTON_RECEIVER, component.flattenToString(),
525 record.getUserId());
526 }
RoboErik6f0e4dd2014-06-17 16:56:27 -0700527 }
528 }
529
RoboErik4646d282014-05-13 10:13:04 -0700530 /**
531 * Information about a particular user. The contents of this object is
532 * guarded by mLock.
533 */
534 final class UserRecord {
535 private final int mUserId;
RoboErik4646d282014-05-13 10:13:04 -0700536 private final ArrayList<MediaSessionRecord> mSessions = new ArrayList<MediaSessionRecord>();
RoboErikc8f92d12015-01-05 16:48:07 -0800537 private final Context mContext;
RoboErikb214efb2014-07-24 13:20:30 -0700538 private PendingIntent mLastMediaButtonReceiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800539 private ComponentName mRestoredMediaButtonReceiver;
RoboErik4646d282014-05-13 10:13:04 -0700540
541 public UserRecord(Context context, int userId) {
RoboErikc8f92d12015-01-05 16:48:07 -0800542 mContext = context;
RoboErik4646d282014-05-13 10:13:04 -0700543 mUserId = userId;
RoboErikc8f92d12015-01-05 16:48:07 -0800544 restoreMediaButtonReceiver();
RoboErik4646d282014-05-13 10:13:04 -0700545 }
546
547 public void startLocked() {
RoboErik4646d282014-05-13 10:13:04 -0700548 }
549
550 public void stopLocked() {
Jeff Brown01a500e2014-07-10 22:50:50 -0700551 // nothing for now
RoboErik4646d282014-05-13 10:13:04 -0700552 }
553
554 public void destroyLocked() {
555 for (int i = mSessions.size() - 1; i >= 0; i--) {
556 MediaSessionRecord session = mSessions.get(i);
557 MediaSessionService.this.destroySessionLocked(session);
RoboErik4646d282014-05-13 10:13:04 -0700558 }
559 }
560
RoboErik4646d282014-05-13 10:13:04 -0700561 public ArrayList<MediaSessionRecord> getSessionsLocked() {
562 return mSessions;
563 }
564
565 public void addSessionLocked(MediaSessionRecord session) {
566 mSessions.add(session);
RoboErik4646d282014-05-13 10:13:04 -0700567 }
568
569 public void removeSessionLocked(MediaSessionRecord session) {
570 mSessions.remove(session);
RoboErik4646d282014-05-13 10:13:04 -0700571 }
572
573 public void dumpLocked(PrintWriter pw, String prefix) {
574 pw.println(prefix + "Record for user " + mUserId);
575 String indent = prefix + " ";
RoboErikb214efb2014-07-24 13:20:30 -0700576 pw.println(indent + "MediaButtonReceiver:" + mLastMediaButtonReceiver);
RoboErikc8f92d12015-01-05 16:48:07 -0800577 pw.println(indent + "Restored ButtonReceiver:" + mRestoredMediaButtonReceiver);
Jeff Brown01a500e2014-07-10 22:50:50 -0700578 int size = mSessions.size();
RoboErik4646d282014-05-13 10:13:04 -0700579 pw.println(indent + size + " Sessions:");
580 for (int i = 0; i < size; i++) {
RoboErikaa4e23b2014-07-24 18:35:11 -0700581 // Just print the short version, the full session dump will
RoboErik4646d282014-05-13 10:13:04 -0700582 // already be in the list of all sessions.
RoboErikaa4e23b2014-07-24 18:35:11 -0700583 pw.println(indent + mSessions.get(i).toString());
RoboErik4646d282014-05-13 10:13:04 -0700584 }
585 }
RoboErikc8f92d12015-01-05 16:48:07 -0800586
587 private void restoreMediaButtonReceiver() {
588 String receiverName = Settings.Secure.getStringForUser(mContentResolver,
589 Settings.System.MEDIA_BUTTON_RECEIVER, UserHandle.USER_CURRENT);
590 if (!TextUtils.isEmpty(receiverName)) {
591 ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
592 if (eventReceiver == null) {
593 // an invalid name was persisted
594 return;
595 }
596 mRestoredMediaButtonReceiver = eventReceiver;
597 }
598 }
RoboErik4646d282014-05-13 10:13:04 -0700599 }
600
RoboErik2e7a9162014-06-04 16:53:45 -0700601 final class SessionsListenerRecord implements IBinder.DeathRecipient {
602 private final IActiveSessionsListener mListener;
RoboErik7aef77b2014-08-08 15:56:54 -0700603 private final ComponentName mComponentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700604 private final int mUserId;
RoboErik7aef77b2014-08-08 15:56:54 -0700605 private final int mPid;
606 private final int mUid;
RoboErik2e7a9162014-06-04 16:53:45 -0700607
RoboErik7aef77b2014-08-08 15:56:54 -0700608 public SessionsListenerRecord(IActiveSessionsListener listener,
609 ComponentName componentName,
610 int userId, int pid, int uid) {
RoboErik2e7a9162014-06-04 16:53:45 -0700611 mListener = listener;
RoboErik7aef77b2014-08-08 15:56:54 -0700612 mComponentName = componentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700613 mUserId = userId;
RoboErik7aef77b2014-08-08 15:56:54 -0700614 mPid = pid;
615 mUid = uid;
RoboErik2e7a9162014-06-04 16:53:45 -0700616 }
617
618 @Override
619 public void binderDied() {
620 synchronized (mLock) {
621 mSessionsListeners.remove(this);
622 }
623 }
624 }
625
RoboErik7aef77b2014-08-08 15:56:54 -0700626 final class SettingsObserver extends ContentObserver {
627 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(
628 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
629
630 private SettingsObserver() {
631 super(null);
632 }
633
634 private void observe() {
635 mContentResolver.registerContentObserver(mSecureSettingsUri,
636 false, this, UserHandle.USER_ALL);
637 }
638
639 @Override
640 public void onChange(boolean selfChange, Uri uri) {
641 updateActiveSessionListeners();
642 }
643 }
644
RoboErik07c70772014-03-20 13:33:52 -0700645 class SessionManagerImpl extends ISessionManager.Stub {
RoboErik8a2cfc32014-05-16 11:19:38 -0700646 private static final String EXTRA_WAKELOCK_ACQUIRED =
647 "android.media.AudioService.WAKELOCK_ACQUIRED";
648 private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; // magic number
649
RoboErik9a9d0b52014-05-20 14:53:39 -0700650 private boolean mVoiceButtonDown = false;
651 private boolean mVoiceButtonHandled = false;
652
RoboErik07c70772014-03-20 13:33:52 -0700653 @Override
RoboErika5b02322014-05-07 17:05:49 -0700654 public ISession createSession(String packageName, ISessionCallback cb, String tag,
655 int userId) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800656 final int pid = Binder.getCallingPid();
657 final int uid = Binder.getCallingUid();
658 final long token = Binder.clearCallingIdentity();
659 try {
660 enforcePackageName(packageName, uid);
RoboErika5b02322014-05-07 17:05:49 -0700661 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
662 false /* allowAll */, true /* requireFull */, "createSession", packageName);
RoboErik01fe6612014-02-13 14:19:04 -0800663 if (cb == null) {
664 throw new IllegalArgumentException("Controller callback cannot be null");
665 }
RoboErika5b02322014-05-07 17:05:49 -0700666 return createSessionInternal(pid, uid, resolvedUserId, packageName, cb, tag)
667 .getSessionBinder();
RoboErike7880d82014-04-30 12:48:25 -0700668 } finally {
669 Binder.restoreCallingIdentity(token);
670 }
671 }
672
673 @Override
RoboErika5b02322014-05-07 17:05:49 -0700674 public List<IBinder> getSessions(ComponentName componentName, int userId) {
RoboErike7880d82014-04-30 12:48:25 -0700675 final int pid = Binder.getCallingPid();
676 final int uid = Binder.getCallingUid();
677 final long token = Binder.clearCallingIdentity();
678
679 try {
RoboErik2e7a9162014-06-04 16:53:45 -0700680 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
RoboErike7880d82014-04-30 12:48:25 -0700681 ArrayList<IBinder> binders = new ArrayList<IBinder>();
682 synchronized (mLock) {
RoboErika8f95142014-05-05 14:23:49 -0700683 ArrayList<MediaSessionRecord> records = mPriorityStack
RoboErika5b02322014-05-07 17:05:49 -0700684 .getActiveSessions(resolvedUserId);
RoboErika8f95142014-05-05 14:23:49 -0700685 int size = records.size();
686 for (int i = 0; i < size; i++) {
687 binders.add(records.get(i).getControllerBinder().asBinder());
RoboErike7880d82014-04-30 12:48:25 -0700688 }
689 }
690 return binders;
RoboErik01fe6612014-02-13 14:19:04 -0800691 } finally {
692 Binder.restoreCallingIdentity(token);
693 }
694 }
RoboErika278ea72014-04-24 14:49:01 -0700695
RoboErik2e7a9162014-06-04 16:53:45 -0700696 @Override
697 public void addSessionsListener(IActiveSessionsListener listener,
698 ComponentName componentName, int userId) throws RemoteException {
699 final int pid = Binder.getCallingPid();
700 final int uid = Binder.getCallingUid();
701 final long token = Binder.clearCallingIdentity();
702
703 try {
704 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
705 synchronized (mLock) {
706 int index = findIndexOfSessionsListenerLocked(listener);
707 if (index != -1) {
708 Log.w(TAG, "ActiveSessionsListener is already added, ignoring");
709 return;
710 }
711 SessionsListenerRecord record = new SessionsListenerRecord(listener,
RoboErik7aef77b2014-08-08 15:56:54 -0700712 componentName, resolvedUserId, pid, uid);
RoboErik2e7a9162014-06-04 16:53:45 -0700713 try {
714 listener.asBinder().linkToDeath(record, 0);
715 } catch (RemoteException e) {
716 Log.e(TAG, "ActiveSessionsListener is dead, ignoring it", e);
717 return;
718 }
719 mSessionsListeners.add(record);
720 }
721 } finally {
722 Binder.restoreCallingIdentity(token);
723 }
724 }
725
726 @Override
727 public void removeSessionsListener(IActiveSessionsListener listener)
728 throws RemoteException {
729 synchronized (mLock) {
730 int index = findIndexOfSessionsListenerLocked(listener);
731 if (index != -1) {
732 SessionsListenerRecord record = mSessionsListeners.remove(index);
733 try {
734 record.mListener.asBinder().unlinkToDeath(record, 0);
735 } catch (Exception e) {
736 // ignore exceptions, the record is being removed
737 }
738 }
739 }
740 }
741
RoboErik8a2cfc32014-05-16 11:19:38 -0700742 /**
743 * Handles the dispatching of the media button events to one of the
744 * registered listeners, or if there was none, broadcast an
745 * ACTION_MEDIA_BUTTON intent to the rest of the system.
746 *
747 * @param keyEvent a non-null KeyEvent whose key code is one of the
748 * supported media buttons
749 * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held
750 * while this key event is dispatched.
751 */
752 @Override
753 public void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
754 if (keyEvent == null || !KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
755 Log.w(TAG, "Attempted to dispatch null or non-media key event.");
756 return;
757 }
758 final int pid = Binder.getCallingPid();
759 final int uid = Binder.getCallingUid();
760 final long token = Binder.clearCallingIdentity();
RoboErike7b3c5e2015-02-11 12:07:01 -0800761 if (DEBUG) {
762 Log.d(TAG, "dispatchMediaKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
763 + keyEvent);
764 }
RoboErik8a2cfc32014-05-16 11:19:38 -0700765
766 try {
RoboErik8a2cfc32014-05-16 11:19:38 -0700767 synchronized (mLock) {
RoboErik870c5a62014-12-02 15:08:26 -0800768 // If we don't have a media button receiver to fall back on
769 // include non-playing sessions for dispatching
RoboErikc8f92d12015-01-05 16:48:07 -0800770 UserRecord ur = mUserRecords.get(ActivityManager.getCurrentUser());
771 boolean useNotPlayingSessions = ur.mLastMediaButtonReceiver == null
772 && ur.mRestoredMediaButtonReceiver == null;
RoboErik9a9d0b52014-05-20 14:53:39 -0700773 MediaSessionRecord session = mPriorityStack
RoboErik870c5a62014-12-02 15:08:26 -0800774 .getDefaultMediaButtonSession(mCurrentUserId, useNotPlayingSessions);
RoboErik9a9d0b52014-05-20 14:53:39 -0700775 if (isVoiceKey(keyEvent.getKeyCode())) {
776 handleVoiceKeyEventLocked(keyEvent, needWakeLock, session);
RoboErik8a2cfc32014-05-16 11:19:38 -0700777 } else {
RoboErik9a9d0b52014-05-20 14:53:39 -0700778 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, session);
RoboErik8a2cfc32014-05-16 11:19:38 -0700779 }
780 }
781 } finally {
782 Binder.restoreCallingIdentity(token);
783 }
784 }
785
RoboErika278ea72014-04-24 14:49:01 -0700786 @Override
RoboErik7c82ced2014-12-04 17:39:08 -0800787 public void dispatchAdjustVolume(int suggestedStream, int delta, int flags) {
RoboErikb69ffd42014-05-30 14:57:59 -0700788 final int pid = Binder.getCallingPid();
789 final int uid = Binder.getCallingUid();
790 final long token = Binder.clearCallingIdentity();
791 try {
792 synchronized (mLock) {
793 MediaSessionRecord session = mPriorityStack
794 .getDefaultVolumeSession(mCurrentUserId);
RoboErik1ff5b162014-07-15 17:23:18 -0700795 dispatchAdjustVolumeLocked(suggestedStream, delta, flags, session);
RoboErikb69ffd42014-05-30 14:57:59 -0700796 }
797 } finally {
798 Binder.restoreCallingIdentity(token);
799 }
800 }
801
802 @Override
RoboErik19c95182014-06-23 15:38:48 -0700803 public void setRemoteVolumeController(IRemoteVolumeController rvc) {
804 final int pid = Binder.getCallingPid();
805 final int uid = Binder.getCallingUid();
806 final long token = Binder.clearCallingIdentity();
807 try {
John Spurlockeb69e242015-02-17 17:15:04 -0500808 enforceSystemUiPermission("listen for volume changes", pid, uid);
RoboErik19c95182014-06-23 15:38:48 -0700809 mRvc = rvc;
810 } finally {
811 Binder.restoreCallingIdentity(token);
812 }
813 }
814
815 @Override
RoboErikde9ba392014-09-26 12:51:01 -0700816 public boolean isGlobalPriorityActive() {
817 return mPriorityStack.isGlobalPriorityActive();
818 }
819
820 @Override
RoboErika278ea72014-04-24 14:49:01 -0700821 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
822 if (getContext().checkCallingOrSelfPermission(Manifest.permission.DUMP)
823 != PackageManager.PERMISSION_GRANTED) {
824 pw.println("Permission Denial: can't dump MediaSessionService from from pid="
825 + Binder.getCallingPid()
826 + ", uid=" + Binder.getCallingUid());
827 return;
828 }
829
830 pw.println("MEDIA SESSION SERVICE (dumpsys media_session)");
831 pw.println();
832
833 synchronized (mLock) {
RoboErika08adb242014-11-21 18:28:18 -0800834 pw.println(mSessionsListeners.size() + " sessions listeners.");
RoboErik4646d282014-05-13 10:13:04 -0700835 int count = mAllSessions.size();
RoboErika8f95142014-05-05 14:23:49 -0700836 pw.println(count + " Sessions:");
RoboErika278ea72014-04-24 14:49:01 -0700837 for (int i = 0; i < count; i++) {
RoboErik4646d282014-05-13 10:13:04 -0700838 mAllSessions.get(i).dump(pw, "");
RoboErika278ea72014-04-24 14:49:01 -0700839 pw.println();
RoboErika278ea72014-04-24 14:49:01 -0700840 }
RoboErika5b02322014-05-07 17:05:49 -0700841 mPriorityStack.dump(pw, "");
RoboErika8f95142014-05-05 14:23:49 -0700842
RoboErik4646d282014-05-13 10:13:04 -0700843 pw.println("User Records:");
844 count = mUserRecords.size();
RoboErika278ea72014-04-24 14:49:01 -0700845 for (int i = 0; i < count; i++) {
RoboErik7b3da2d2015-02-02 15:21:29 -0800846 UserRecord user = mUserRecords.get(mUserRecords.keyAt(i));
RoboErik4646d282014-05-13 10:13:04 -0700847 user.dumpLocked(pw, "");
RoboErika278ea72014-04-24 14:49:01 -0700848 }
849 }
850 }
RoboErik8a2cfc32014-05-16 11:19:38 -0700851
RoboErik2e7a9162014-06-04 16:53:45 -0700852 private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
853 final int uid) {
854 String packageName = null;
855 if (componentName != null) {
856 // If they gave us a component name verify they own the
857 // package
858 packageName = componentName.getPackageName();
859 enforcePackageName(packageName, uid);
860 }
861 // Check that they can make calls on behalf of the user and
862 // get the final user id
863 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
864 true /* allowAll */, true /* requireFull */, "getSessions", packageName);
865 // Check if they have the permissions or their component is
866 // enabled for the user they're calling from.
867 enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
868 return resolvedUserId;
869 }
870
RoboErik1ff5b162014-07-15 17:23:18 -0700871 private void dispatchAdjustVolumeLocked(int suggestedStream, int direction, int flags,
RoboErikb69ffd42014-05-30 14:57:59 -0700872 MediaSessionRecord session) {
RoboErikb69ffd42014-05-30 14:57:59 -0700873 if (DEBUG) {
RoboErikaa4e23b2014-07-24 18:35:11 -0700874 String description = session == null ? null : session.toString();
875 Log.d(TAG, "Adjusting session " + description + " by " + direction + ". flags="
876 + flags + ", suggestedStream=" + suggestedStream);
RoboErikb69ffd42014-05-30 14:57:59 -0700877
878 }
RoboErik9c785402014-11-11 16:52:26 -0800879 boolean preferSuggestedStream = false;
880 if (isValidLocalStreamType(suggestedStream)
881 && AudioSystem.isStreamActive(suggestedStream, 0)) {
882 preferSuggestedStream = true;
883 }
884 if (session == null || preferSuggestedStream) {
RoboErik94c716e2014-09-14 13:54:31 -0700885 if ((flags & AudioManager.FLAG_ACTIVE_MEDIA_ONLY) != 0
886 && !AudioSystem.isStreamActive(AudioManager.STREAM_MUSIC, 0)) {
RoboErik3c45c292014-07-08 16:47:31 -0700887 if (DEBUG) {
888 Log.d(TAG, "No active session to adjust, skipping media only volume event");
RoboErik3c45c292014-07-08 16:47:31 -0700889 }
RoboErikb7c014c2014-07-22 15:58:22 -0700890 return;
RoboErik3c45c292014-07-08 16:47:31 -0700891 }
RoboErik0791e172014-06-08 10:52:32 -0700892 try {
Eric Laurent2b5208c2014-12-19 10:07:03 -0800893 String packageName = getContext().getOpPackageName();
RoboErik519c7742014-11-18 10:59:09 -0800894 if (mUseMasterVolume) {
Eric Laurent2b5208c2014-12-19 10:07:03 -0800895 mAudioService.adjustMasterVolume(direction, flags, packageName);
RoboErik519c7742014-11-18 10:59:09 -0800896 } else {
RoboErik4197cb62015-01-21 15:45:32 -0800897 mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
898 flags, packageName);
RoboErik519c7742014-11-18 10:59:09 -0800899 }
RoboErik0791e172014-06-08 10:52:32 -0700900 } catch (RemoteException e) {
901 Log.e(TAG, "Error adjusting default volume.", e);
RoboErikb69ffd42014-05-30 14:57:59 -0700902 }
903 } else {
RoboErik0dac35a2014-08-12 15:48:49 -0700904 session.adjustVolume(direction, flags, getContext().getPackageName(),
RoboErik272e1612014-09-05 11:39:29 -0700905 UserHandle.myUserId(), true);
RoboErikb69ffd42014-05-30 14:57:59 -0700906 }
907 }
908
RoboErik9a9d0b52014-05-20 14:53:39 -0700909 private void handleVoiceKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock,
910 MediaSessionRecord session) {
911 if (session != null && session.hasFlag(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY)) {
912 // If the phone app has priority just give it the event
913 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, session);
914 return;
915 }
916 int action = keyEvent.getAction();
917 boolean isLongPress = (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0;
918 if (action == KeyEvent.ACTION_DOWN) {
919 if (keyEvent.getRepeatCount() == 0) {
920 mVoiceButtonDown = true;
921 mVoiceButtonHandled = false;
922 } else if (mVoiceButtonDown && !mVoiceButtonHandled && isLongPress) {
923 mVoiceButtonHandled = true;
924 startVoiceInput(needWakeLock);
925 }
926 } else if (action == KeyEvent.ACTION_UP) {
927 if (mVoiceButtonDown) {
928 mVoiceButtonDown = false;
929 if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
930 // Resend the down then send this event through
931 KeyEvent downEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_DOWN);
932 dispatchMediaKeyEventLocked(downEvent, needWakeLock, session);
933 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, session);
934 }
935 }
936 }
937 }
938
939 private void dispatchMediaKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock,
940 MediaSessionRecord session) {
941 if (session != null) {
942 if (DEBUG) {
RoboErikaa4e23b2014-07-24 18:35:11 -0700943 Log.d(TAG, "Sending media key to " + session.toString());
RoboErik9a9d0b52014-05-20 14:53:39 -0700944 }
945 if (needWakeLock) {
946 mKeyEventReceiver.aquireWakeLockLocked();
947 }
948 // If we don't need a wakelock use -1 as the id so we
949 // won't release it later
950 session.sendMediaButton(keyEvent,
951 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
952 mKeyEventReceiver);
953 } else {
RoboErikb214efb2014-07-24 13:20:30 -0700954 // Launch the last PendingIntent we had with priority
955 int userId = ActivityManager.getCurrentUser();
956 UserRecord user = mUserRecords.get(userId);
RoboErikc8f92d12015-01-05 16:48:07 -0800957 if (user.mLastMediaButtonReceiver != null
958 || user.mRestoredMediaButtonReceiver != null) {
RoboErikb214efb2014-07-24 13:20:30 -0700959 if (DEBUG) {
RoboErikc8f92d12015-01-05 16:48:07 -0800960 Log.d(TAG, "Sending media key to last known PendingIntent "
961 + user.mLastMediaButtonReceiver + " or restored Intent "
962 + user.mRestoredMediaButtonReceiver);
RoboErikb214efb2014-07-24 13:20:30 -0700963 }
964 if (needWakeLock) {
965 mKeyEventReceiver.aquireWakeLockLocked();
966 }
967 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
968 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
969 try {
RoboErikc8f92d12015-01-05 16:48:07 -0800970 if (user.mLastMediaButtonReceiver != null) {
971 user.mLastMediaButtonReceiver.send(getContext(),
972 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
973 mediaButtonIntent, mKeyEventReceiver, null);
974 } else {
975 mediaButtonIntent.setComponent(user.mRestoredMediaButtonReceiver);
976 getContext().sendBroadcastAsUser(mediaButtonIntent,
977 new UserHandle(userId));
978 }
RoboErikb214efb2014-07-24 13:20:30 -0700979 } catch (CanceledException e) {
980 Log.i(TAG, "Error sending key event to media button receiver "
981 + user.mLastMediaButtonReceiver, e);
982 }
983 } else {
984 if (DEBUG) {
985 Log.d(TAG, "Sending media key ordered broadcast");
986 }
987 if (needWakeLock) {
988 mMediaEventWakeLock.acquire();
989 }
990 // Fallback to legacy behavior
991 Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
992 keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
993 if (needWakeLock) {
994 keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED,
995 WAKELOCK_RELEASE_ON_FINISHED);
996 }
997 getContext().sendOrderedBroadcastAsUser(keyIntent, UserHandle.ALL,
998 null, mKeyEventDone, mHandler, Activity.RESULT_OK, null, null);
RoboErik9a9d0b52014-05-20 14:53:39 -0700999 }
RoboErik9a9d0b52014-05-20 14:53:39 -07001000 }
1001 }
1002
1003 private void startVoiceInput(boolean needWakeLock) {
1004 Intent voiceIntent = null;
1005 // select which type of search to launch:
1006 // - screen on and device unlocked: action is ACTION_WEB_SEARCH
1007 // - device locked or screen off: action is
1008 // ACTION_VOICE_SEARCH_HANDS_FREE
1009 // with EXTRA_SECURE set to true if the device is securely locked
1010 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1011 boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
1012 if (!isLocked && pm.isScreenOn()) {
1013 voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
1014 Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
1015 } else {
1016 voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
1017 voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
1018 isLocked && mKeyguardManager.isKeyguardSecure());
1019 Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
1020 }
1021 // start the search activity
1022 if (needWakeLock) {
1023 mMediaEventWakeLock.acquire();
1024 }
1025 try {
1026 if (voiceIntent != null) {
1027 voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1028 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1029 getContext().startActivityAsUser(voiceIntent, UserHandle.CURRENT);
1030 }
1031 } catch (ActivityNotFoundException e) {
1032 Log.w(TAG, "No activity for search: " + e);
1033 } finally {
1034 if (needWakeLock) {
1035 mMediaEventWakeLock.release();
1036 }
1037 }
1038 }
1039
1040 private boolean isVoiceKey(int keyCode) {
1041 return keyCode == KeyEvent.KEYCODE_HEADSETHOOK;
1042 }
1043
RoboErik9c785402014-11-11 16:52:26 -08001044 // we only handle public stream types, which are 0-5
1045 private boolean isValidLocalStreamType(int streamType) {
1046 return streamType >= AudioManager.STREAM_VOICE_CALL
1047 && streamType <= AudioManager.STREAM_NOTIFICATION;
1048 }
1049
RoboErik418c10c2014-05-19 09:25:25 -07001050 private KeyEventWakeLockReceiver mKeyEventReceiver = new KeyEventWakeLockReceiver(mHandler);
1051
RoboErikb214efb2014-07-24 13:20:30 -07001052 class KeyEventWakeLockReceiver extends ResultReceiver implements Runnable,
1053 PendingIntent.OnFinished {
RoboErik418c10c2014-05-19 09:25:25 -07001054 private final Handler mHandler;
1055 private int mRefCount = 0;
1056 private int mLastTimeoutId = 0;
1057
1058 public KeyEventWakeLockReceiver(Handler handler) {
1059 super(handler);
1060 mHandler = handler;
1061 }
1062
1063 public void onTimeout() {
1064 synchronized (mLock) {
1065 if (mRefCount == 0) {
1066 // We've already released it, so just return
1067 return;
1068 }
1069 mLastTimeoutId++;
1070 mRefCount = 0;
1071 releaseWakeLockLocked();
1072 }
1073 }
1074
1075 public void aquireWakeLockLocked() {
1076 if (mRefCount == 0) {
1077 mMediaEventWakeLock.acquire();
1078 }
1079 mRefCount++;
1080 mHandler.removeCallbacks(this);
1081 mHandler.postDelayed(this, WAKELOCK_TIMEOUT);
1082
1083 }
1084
1085 @Override
1086 public void run() {
1087 onTimeout();
1088 }
1089
RoboErik8a2cfc32014-05-16 11:19:38 -07001090 @Override
1091 protected void onReceiveResult(int resultCode, Bundle resultData) {
RoboErik418c10c2014-05-19 09:25:25 -07001092 if (resultCode < mLastTimeoutId) {
1093 // Ignore results from calls that were before the last
1094 // timeout, just in case.
1095 return;
1096 } else {
1097 synchronized (mLock) {
1098 if (mRefCount > 0) {
1099 mRefCount--;
1100 if (mRefCount == 0) {
1101 releaseWakeLockLocked();
1102 }
1103 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001104 }
1105 }
1106 }
RoboErik418c10c2014-05-19 09:25:25 -07001107
1108 private void releaseWakeLockLocked() {
1109 mMediaEventWakeLock.release();
1110 mHandler.removeCallbacks(this);
1111 }
RoboErikb214efb2014-07-24 13:20:30 -07001112
1113 @Override
1114 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
1115 String resultData, Bundle resultExtras) {
1116 onReceiveResult(resultCode, null);
1117 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001118 };
1119
1120 BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
1121 @Override
1122 public void onReceive(Context context, Intent intent) {
1123 if (intent == null) {
1124 return;
1125 }
1126 Bundle extras = intent.getExtras();
1127 if (extras == null) {
1128 return;
1129 }
1130 synchronized (mLock) {
1131 if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)
1132 && mMediaEventWakeLock.isHeld()) {
1133 mMediaEventWakeLock.release();
1134 }
1135 }
1136 }
1137 };
RoboErik01fe6612014-02-13 14:19:04 -08001138 }
1139
RoboErik2e7a9162014-06-04 16:53:45 -07001140 final class MessageHandler extends Handler {
1141 private static final int MSG_SESSIONS_CHANGED = 1;
1142
1143 @Override
1144 public void handleMessage(Message msg) {
1145 switch (msg.what) {
1146 case MSG_SESSIONS_CHANGED:
1147 pushSessionsChanged(msg.arg1);
1148 break;
1149 }
1150 }
1151
1152 public void post(int what, int arg1, int arg2) {
1153 obtainMessage(what, arg1, arg2).sendToTarget();
1154 }
1155 }
RoboErik01fe6612014-02-13 14:19:04 -08001156}