blob: dfa2f863d0683a377dc0bb28c9b435bad47890ac [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;
Jaewan Kim50269362016-12-23 11:22:02 +090020import android.annotation.NonNull;
RoboErik8a2cfc32014-05-16 11:19:38 -070021import android.app.Activity;
RoboErike7880d82014-04-30 12:48:25 -070022import android.app.ActivityManager;
RoboErik9a9d0b52014-05-20 14:53:39 -070023import android.app.KeyguardManager;
RoboErikb214efb2014-07-24 13:20:30 -070024import android.app.PendingIntent;
25import android.app.PendingIntent.CanceledException;
RoboErik9a9d0b52014-05-20 14:53:39 -070026import android.content.ActivityNotFoundException;
RoboErik8a2cfc32014-05-16 11:19:38 -070027import android.content.BroadcastReceiver;
RoboErike7880d82014-04-30 12:48:25 -070028import android.content.ComponentName;
RoboErik6f0e4dd2014-06-17 16:56:27 -070029import android.content.ContentResolver;
RoboErik01fe6612014-02-13 14:19:04 -080030import android.content.Context;
RoboErik8a2cfc32014-05-16 11:19:38 -070031import android.content.Intent;
RoboErika278ea72014-04-24 14:49:01 -070032import android.content.pm.PackageManager;
RoboErik7aef77b2014-08-08 15:56:54 -070033import android.database.ContentObserver;
RoboErik3c45c292014-07-08 16:47:31 -070034import android.media.AudioManager;
John Spurlockeb69e242015-02-17 17:15:04 -050035import android.media.AudioManagerInternal;
RoboErik94c716e2014-09-14 13:54:31 -070036import android.media.AudioSystem;
RoboErikb69ffd42014-05-30 14:57:59 -070037import android.media.IAudioService;
RoboErik19c95182014-06-23 15:38:48 -070038import android.media.IRemoteVolumeController;
RoboErik2e7a9162014-06-04 16:53:45 -070039import android.media.session.IActiveSessionsListener;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080040import android.media.session.IOnMediaKeyListener;
Jaewan Kim50269362016-12-23 11:22:02 +090041import android.media.session.IOnVolumeKeyLongPressListener;
RoboErik07c70772014-03-20 13:33:52 -070042import android.media.session.ISession;
43import android.media.session.ISessionCallback;
44import android.media.session.ISessionManager;
Jeff Browndba34ba2014-06-24 20:46:03 -070045import android.media.session.MediaSession;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080046import android.media.session.MediaSessionManager;
RoboErik7aef77b2014-08-08 15:56:54 -070047import android.net.Uri;
RoboErik01fe6612014-02-13 14:19:04 -080048import android.os.Binder;
RoboErik8a2cfc32014-05-16 11:19:38 -070049import android.os.Bundle;
RoboErik8ae0f342014-02-24 18:02:08 -080050import android.os.Handler;
RoboErike7880d82014-04-30 12:48:25 -070051import android.os.IBinder;
RoboErik2e7a9162014-06-04 16:53:45 -070052import android.os.Message;
RoboErik8a2cfc32014-05-16 11:19:38 -070053import android.os.PowerManager;
Jaewan Kim8f729082016-06-21 12:36:26 +090054import android.os.Process;
RoboErik01fe6612014-02-13 14:19:04 -080055import android.os.RemoteException;
RoboErik8a2cfc32014-05-16 11:19:38 -070056import android.os.ResultReceiver;
RoboErikb69ffd42014-05-30 14:57:59 -070057import android.os.ServiceManager;
RoboErike7880d82014-04-30 12:48:25 -070058import android.os.UserHandle;
Jaewan Kim8f729082016-06-21 12:36:26 +090059import android.os.UserManager;
RoboErike7880d82014-04-30 12:48:25 -070060import android.provider.Settings;
RoboErik9a9d0b52014-05-20 14:53:39 -070061import android.speech.RecognizerIntent;
RoboErik01fe6612014-02-13 14:19:04 -080062import android.text.TextUtils;
63import android.util.Log;
Jeff Brown38d3feb2015-03-19 18:26:30 -070064import android.util.Slog;
RoboErik4646d282014-05-13 10:13:04 -070065import android.util.SparseArray;
RoboErik8a2cfc32014-05-16 11:19:38 -070066import android.view.KeyEvent;
Jaewan Kimd61a87b2017-02-17 23:14:10 +090067import android.view.ViewConfiguration;
RoboErik01fe6612014-02-13 14:19:04 -080068
John Spurlockeb69e242015-02-17 17:15:04 -050069import com.android.server.LocalServices;
RoboErik01fe6612014-02-13 14:19:04 -080070import com.android.server.SystemService;
RoboErika278ea72014-04-24 14:49:01 -070071import com.android.server.Watchdog;
72import com.android.server.Watchdog.Monitor;
RoboErik01fe6612014-02-13 14:19:04 -080073
RoboErika278ea72014-04-24 14:49:01 -070074import java.io.FileDescriptor;
75import java.io.PrintWriter;
RoboErik01fe6612014-02-13 14:19:04 -080076import java.util.ArrayList;
Jaewan Kim8f729082016-06-21 12:36:26 +090077import java.util.Arrays;
RoboErike7880d82014-04-30 12:48:25 -070078import java.util.List;
RoboErik01fe6612014-02-13 14:19:04 -080079
80/**
81 * System implementation of MediaSessionManager
82 */
RoboErika278ea72014-04-24 14:49:01 -070083public class MediaSessionService extends SystemService implements Monitor {
RoboErik01fe6612014-02-13 14:19:04 -080084 private static final String TAG = "MediaSessionService";
85 private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
Jaewan Kim50269362016-12-23 11:22:02 +090086 // Leave log for key event always.
87 private static final boolean DEBUG_KEY_EVENT = true;
RoboErik01fe6612014-02-13 14:19:04 -080088
RoboErik418c10c2014-05-19 09:25:25 -070089 private static final int WAKELOCK_TIMEOUT = 5000;
Jaewan Kim6e2b01c2017-01-19 16:33:14 -080090 private static final int MEDIA_KEY_LISTENER_TIMEOUT = 1000;
RoboErik418c10c2014-05-19 09:25:25 -070091
RoboErik2610d712015-01-07 11:10:23 -080092 /* package */final IBinder mICallback = new Binder();
93
RoboErik01fe6612014-02-13 14:19:04 -080094 private final SessionManagerImpl mSessionManagerImpl;
RoboErika8f95142014-05-05 14:23:49 -070095 private final MediaSessionStack mPriorityStack;
RoboErik01fe6612014-02-13 14:19:04 -080096
RoboErik4646d282014-05-13 10:13:04 -070097 private final SparseArray<UserRecord> mUserRecords = new SparseArray<UserRecord>();
RoboErik2e7a9162014-06-04 16:53:45 -070098 private final ArrayList<SessionsListenerRecord> mSessionsListeners
99 = new ArrayList<SessionsListenerRecord>();
RoboErik01fe6612014-02-13 14:19:04 -0800100 private final Object mLock = new Object();
RoboErik2e7a9162014-06-04 16:53:45 -0700101 private final MessageHandler mHandler = new MessageHandler();
RoboErik8a2cfc32014-05-16 11:19:38 -0700102 private final PowerManager.WakeLock mMediaEventWakeLock;
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900103 private final int mLongPressTimeout;
RoboErik01fe6612014-02-13 14:19:04 -0800104
RoboErik9a9d0b52014-05-20 14:53:39 -0700105 private KeyguardManager mKeyguardManager;
RoboErikb69ffd42014-05-30 14:57:59 -0700106 private IAudioService mAudioService;
John Spurlockeb69e242015-02-17 17:15:04 -0500107 private AudioManagerInternal mAudioManagerInternal;
RoboErik6f0e4dd2014-06-17 16:56:27 -0700108 private ContentResolver mContentResolver;
RoboErik7aef77b2014-08-08 15:56:54 -0700109 private SettingsObserver mSettingsObserver;
RoboErik9a9d0b52014-05-20 14:53:39 -0700110
Jaewan Kim8f729082016-06-21 12:36:26 +0900111 // List of user IDs running in the foreground.
112 // Multiple users can be in the foreground if the work profile is on.
113 private final List<Integer> mCurrentUserIdList = new ArrayList<>();
RoboErike7880d82014-04-30 12:48:25 -0700114
RoboErik19c95182014-06-23 15:38:48 -0700115 // Used to notify system UI when remote volume was changed. TODO find a
116 // better way to handle this.
117 private IRemoteVolumeController mRvc;
118
RoboErik01fe6612014-02-13 14:19:04 -0800119 public MediaSessionService(Context context) {
120 super(context);
121 mSessionManagerImpl = new SessionManagerImpl();
RoboErika8f95142014-05-05 14:23:49 -0700122 mPriorityStack = new MediaSessionStack();
RoboErik8a2cfc32014-05-16 11:19:38 -0700123 PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
124 mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900125 mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
RoboErik01fe6612014-02-13 14:19:04 -0800126 }
127
128 @Override
129 public void onStart() {
130 publishBinderService(Context.MEDIA_SESSION_SERVICE, mSessionManagerImpl);
RoboErika278ea72014-04-24 14:49:01 -0700131 Watchdog.getInstance().addMonitor(this);
RoboErik9a9d0b52014-05-20 14:53:39 -0700132 mKeyguardManager =
133 (KeyguardManager) getContext().getSystemService(Context.KEYGUARD_SERVICE);
RoboErikb69ffd42014-05-30 14:57:59 -0700134 mAudioService = getAudioService();
John Spurlockeb69e242015-02-17 17:15:04 -0500135 mAudioManagerInternal = LocalServices.getService(AudioManagerInternal.class);
RoboErik6f0e4dd2014-06-17 16:56:27 -0700136 mContentResolver = getContext().getContentResolver();
RoboErik7aef77b2014-08-08 15:56:54 -0700137 mSettingsObserver = new SettingsObserver();
138 mSettingsObserver.observe();
RoboErikc8f92d12015-01-05 16:48:07 -0800139
140 updateUser();
RoboErikb69ffd42014-05-30 14:57:59 -0700141 }
142
143 private IAudioService getAudioService() {
144 IBinder b = ServiceManager.getService(Context.AUDIO_SERVICE);
145 return IAudioService.Stub.asInterface(b);
RoboErik07c70772014-03-20 13:33:52 -0700146 }
147
RoboErika8f95142014-05-05 14:23:49 -0700148 public void updateSession(MediaSessionRecord record) {
RoboErike7880d82014-04-30 12:48:25 -0700149 synchronized (mLock) {
Jaewan Kime0ca3f32017-02-16 15:52:39 +0900150 UserRecord user = mUserRecords.get(record.getUserId());
151 if (user == null || !user.mSessions.contains(record)) {
RoboErik4646d282014-05-13 10:13:04 -0700152 Log.d(TAG, "Unknown session updated. Ignoring.");
153 return;
154 }
RoboErika8f95142014-05-05 14:23:49 -0700155 mPriorityStack.onSessionStateChange(record);
RoboErike7880d82014-04-30 12:48:25 -0700156 }
RoboErik2e7a9162014-06-04 16:53:45 -0700157 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, record.getUserId(), 0);
RoboErike7880d82014-04-30 12:48:25 -0700158 }
159
RoboErik9c5b7cb2015-01-15 15:09:09 -0800160 /**
Hyundo Moona055f132017-01-13 15:31:06 +0900161 * Tells the system UI that volume has changed on an active remote session.
RoboErik9c5b7cb2015-01-15 15:09:09 -0800162 */
163 public void notifyRemoteVolumeChanged(int flags, MediaSessionRecord session) {
Hyundo Moona055f132017-01-13 15:31:06 +0900164 if (mRvc == null || !session.isActive()) {
RoboErik9c5b7cb2015-01-15 15:09:09 -0800165 return;
166 }
167 try {
168 mRvc.remoteVolumeChanged(session.getControllerBinder(), flags);
169 } catch (Exception e) {
170 Log.wtf(TAG, "Error sending volume change to system UI.", e);
171 }
172 }
173
RoboErika8f95142014-05-05 14:23:49 -0700174 public void onSessionPlaystateChange(MediaSessionRecord record, int oldState, int newState) {
RoboErik2e7a9162014-06-04 16:53:45 -0700175 boolean updateSessions = false;
RoboErika8f95142014-05-05 14:23:49 -0700176 synchronized (mLock) {
Jaewan Kime0ca3f32017-02-16 15:52:39 +0900177 UserRecord user = mUserRecords.get(record.getUserId());
178 if (user == null || !user.mSessions.contains(record)) {
RoboErik4646d282014-05-13 10:13:04 -0700179 Log.d(TAG, "Unknown session changed playback state. Ignoring.");
180 return;
181 }
RoboErik2e7a9162014-06-04 16:53:45 -0700182 updateSessions = mPriorityStack.onPlaystateChange(record, oldState, newState);
183 }
184 if (updateSessions) {
185 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, record.getUserId(), 0);
RoboErika8f95142014-05-05 14:23:49 -0700186 }
187 }
188
RoboErik19c95182014-06-23 15:38:48 -0700189 public void onSessionPlaybackTypeChanged(MediaSessionRecord record) {
190 synchronized (mLock) {
Jaewan Kime0ca3f32017-02-16 15:52:39 +0900191 UserRecord user = mUserRecords.get(record.getUserId());
192 if (user == null || !user.mSessions.contains(record)) {
RoboErik19c95182014-06-23 15:38:48 -0700193 Log.d(TAG, "Unknown session changed playback type. Ignoring.");
194 return;
195 }
196 pushRemoteVolumeUpdateLocked(record.getUserId());
197 }
198 }
199
RoboErika278ea72014-04-24 14:49:01 -0700200 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900201 public void onStartUser(int userId) {
202 if (DEBUG) Log.d(TAG, "onStartUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700203 updateUser();
204 }
205
206 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900207 public void onSwitchUser(int userId) {
208 if (DEBUG) Log.d(TAG, "onSwitchUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700209 updateUser();
210 }
211
212 @Override
Jaewan Kim8f729082016-06-21 12:36:26 +0900213 public void onStopUser(int userId) {
214 if (DEBUG) Log.d(TAG, "onStopUser: " + userId);
RoboErik4646d282014-05-13 10:13:04 -0700215 synchronized (mLock) {
Jaewan Kim8f729082016-06-21 12:36:26 +0900216 UserRecord user = mUserRecords.get(userId);
RoboErik4646d282014-05-13 10:13:04 -0700217 if (user != null) {
218 destroyUserLocked(user);
219 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900220 updateUser();
RoboErik4646d282014-05-13 10:13:04 -0700221 }
222 }
223
224 @Override
RoboErika278ea72014-04-24 14:49:01 -0700225 public void monitor() {
226 synchronized (mLock) {
227 // Check for deadlock
228 }
229 }
230
RoboErik4646d282014-05-13 10:13:04 -0700231 protected void enforcePhoneStatePermission(int pid, int uid) {
232 if (getContext().checkPermission(android.Manifest.permission.MODIFY_PHONE_STATE, pid, uid)
233 != PackageManager.PERMISSION_GRANTED) {
234 throw new SecurityException("Must hold the MODIFY_PHONE_STATE permission.");
235 }
236 }
237
RoboErik01fe6612014-02-13 14:19:04 -0800238 void sessionDied(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700239 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800240 destroySessionLocked(session);
241 }
242 }
243
244 void destroySession(MediaSessionRecord session) {
RoboErika278ea72014-04-24 14:49:01 -0700245 synchronized (mLock) {
RoboErik01fe6612014-02-13 14:19:04 -0800246 destroySessionLocked(session);
247 }
248 }
249
RoboErik4646d282014-05-13 10:13:04 -0700250 private void updateUser() {
251 synchronized (mLock) {
Jaewan Kim8f729082016-06-21 12:36:26 +0900252 UserManager manager = (UserManager) getContext().getSystemService(Context.USER_SERVICE);
253 int currentUser = ActivityManager.getCurrentUser();
Dongwon Kang8cf39c52016-07-29 13:20:39 -0700254 // Include all profiles even though they aren't yet enabled to handle work profile case.
255 int[] userIds = manager.getProfileIdsWithDisabled(currentUser);
Jaewan Kim8f729082016-06-21 12:36:26 +0900256 mCurrentUserIdList.clear();
257 if (userIds != null && userIds.length > 0) {
258 for (int userId : userIds) {
259 mCurrentUserIdList.add(userId);
RoboErik4646d282014-05-13 10:13:04 -0700260 }
Jaewan Kim8f729082016-06-21 12:36:26 +0900261 } else {
262 // This shouldn't happen.
263 Log.w(TAG, "Failed to get enabled profiles.");
264 mCurrentUserIdList.add(currentUser);
265 }
266 for (int userId : mCurrentUserIdList) {
267 if (mUserRecords.get(userId) == null) {
268 mUserRecords.put(userId, new UserRecord(getContext(), userId));
269 }
RoboErik4646d282014-05-13 10:13:04 -0700270 }
271 }
272 }
273
RoboErik7aef77b2014-08-08 15:56:54 -0700274 private void updateActiveSessionListeners() {
275 synchronized (mLock) {
276 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
277 SessionsListenerRecord listener = mSessionsListeners.get(i);
278 try {
279 enforceMediaPermissions(listener.mComponentName, listener.mPid, listener.mUid,
280 listener.mUserId);
281 } catch (SecurityException e) {
282 Log.i(TAG, "ActiveSessionsListener " + listener.mComponentName
283 + " is no longer authorized. Disconnecting.");
284 mSessionsListeners.remove(i);
285 try {
286 listener.mListener
287 .onActiveSessionsChanged(new ArrayList<MediaSession.Token>());
288 } catch (Exception e1) {
289 // ignore
290 }
291 }
292 }
293 }
294 }
295
RoboErik4646d282014-05-13 10:13:04 -0700296 /**
297 * Stop the user and unbind from everything.
298 *
299 * @param user The user to dispose of
300 */
301 private void destroyUserLocked(UserRecord user) {
RoboErik4646d282014-05-13 10:13:04 -0700302 user.destroyLocked();
303 mUserRecords.remove(user.mUserId);
304 }
305
306 /*
307 * When a session is removed several things need to happen.
308 * 1. We need to remove it from the relevant user.
309 * 2. We need to remove it from the priority stack.
310 * 3. We need to remove it from all sessions.
311 * 4. If this is the system priority session we need to clear it.
312 * 5. We need to unlink to death from the cb binder
313 * 6. We need to tell the session to do any final cleanup (onDestroy)
314 */
RoboErik01fe6612014-02-13 14:19:04 -0800315 private void destroySessionLocked(MediaSessionRecord session) {
Insun Kang30be970a2015-11-26 15:35:44 +0900316 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900317 Log.d(TAG, "Destroying " + session);
Insun Kang30be970a2015-11-26 15:35:44 +0900318 }
RoboErik4646d282014-05-13 10:13:04 -0700319 int userId = session.getUserId();
320 UserRecord user = mUserRecords.get(userId);
321 if (user != null) {
322 user.removeSessionLocked(session);
323 }
324
RoboErika8f95142014-05-05 14:23:49 -0700325 mPriorityStack.removeSession(session);
RoboErik4646d282014-05-13 10:13:04 -0700326
327 try {
328 session.getCallback().asBinder().unlinkToDeath(session, 0);
329 } catch (Exception e) {
330 // ignore exceptions while destroying a session.
331 }
332 session.onDestroy();
RoboErik2e7a9162014-06-04 16:53:45 -0700333
334 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, session.getUserId(), 0);
RoboErik01fe6612014-02-13 14:19:04 -0800335 }
336
337 private void enforcePackageName(String packageName, int uid) {
338 if (TextUtils.isEmpty(packageName)) {
339 throw new IllegalArgumentException("packageName may not be empty");
340 }
341 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
342 final int packageCount = packages.length;
343 for (int i = 0; i < packageCount; i++) {
344 if (packageName.equals(packages[i])) {
345 return;
346 }
347 }
348 throw new IllegalArgumentException("packageName is not owned by the calling process");
349 }
350
RoboErike7880d82014-04-30 12:48:25 -0700351 /**
352 * Checks a caller's authorization to register an IRemoteControlDisplay.
353 * Authorization is granted if one of the following is true:
354 * <ul>
355 * <li>the caller has android.Manifest.permission.MEDIA_CONTENT_CONTROL
356 * permission</li>
RoboErika5b02322014-05-07 17:05:49 -0700357 * <li>the caller's listener is one of the enabled notification listeners
358 * for the caller's user</li>
RoboErike7880d82014-04-30 12:48:25 -0700359 * </ul>
360 */
RoboErika5b02322014-05-07 17:05:49 -0700361 private void enforceMediaPermissions(ComponentName compName, int pid, int uid,
362 int resolvedUserId) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500363 if (isCurrentVolumeController(uid, pid)) return;
RoboErike7880d82014-04-30 12:48:25 -0700364 if (getContext()
365 .checkPermission(android.Manifest.permission.MEDIA_CONTENT_CONTROL, pid, uid)
366 != PackageManager.PERMISSION_GRANTED
RoboErika5b02322014-05-07 17:05:49 -0700367 && !isEnabledNotificationListener(compName, UserHandle.getUserId(uid),
368 resolvedUserId)) {
RoboErike7880d82014-04-30 12:48:25 -0700369 throw new SecurityException("Missing permission to control media.");
370 }
371 }
372
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500373 private boolean isCurrentVolumeController(int uid, int pid) {
374 return getContext().checkPermission(android.Manifest.permission.STATUS_BAR_SERVICE,
375 pid, uid) == PackageManager.PERMISSION_GRANTED;
John Spurlockbe19ed02015-02-22 10:57:55 -0500376 }
377
378 private void enforceSystemUiPermission(String action, int pid, int uid) {
Julia Reynoldsbb983d202017-01-06 09:54:20 -0500379 if (!isCurrentVolumeController(uid, pid)) {
RoboErik19c95182014-06-23 15:38:48 -0700380 throw new SecurityException("Only system ui may " + action);
381 }
382 }
383
RoboErika5b02322014-05-07 17:05:49 -0700384 /**
385 * This checks if the component is an enabled notification listener for the
386 * specified user. Enabled components may only operate on behalf of the user
387 * they're running as.
388 *
389 * @param compName The component that is enabled.
390 * @param userId The user id of the caller.
391 * @param forUserId The user id they're making the request on behalf of.
392 * @return True if the component is enabled, false otherwise
393 */
394 private boolean isEnabledNotificationListener(ComponentName compName, int userId,
395 int forUserId) {
396 if (userId != forUserId) {
397 // You may not access another user's content as an enabled listener.
398 return false;
399 }
RoboErik51fa6bc2014-06-20 14:59:58 -0700400 if (DEBUG) {
401 Log.d(TAG, "Checking if enabled notification listener " + compName);
402 }
RoboErike7880d82014-04-30 12:48:25 -0700403 if (compName != null) {
RoboErik6f0e4dd2014-06-17 16:56:27 -0700404 final String enabledNotifListeners = Settings.Secure.getStringForUser(mContentResolver,
RoboErike7880d82014-04-30 12:48:25 -0700405 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS,
RoboErika5b02322014-05-07 17:05:49 -0700406 userId);
RoboErike7880d82014-04-30 12:48:25 -0700407 if (enabledNotifListeners != null) {
408 final String[] components = enabledNotifListeners.split(":");
409 for (int i = 0; i < components.length; i++) {
410 final ComponentName component =
411 ComponentName.unflattenFromString(components[i]);
412 if (component != null) {
413 if (compName.equals(component)) {
414 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900415 Log.d(TAG, "ok to get sessions. " + component +
RoboErike7880d82014-04-30 12:48:25 -0700416 " is authorized notification listener");
417 }
418 return true;
419 }
420 }
421 }
422 }
423 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900424 Log.d(TAG, "not ok to get sessions. " + compName +
RoboErika5b02322014-05-07 17:05:49 -0700425 " is not in list of ENABLED_NOTIFICATION_LISTENERS for user " + userId);
RoboErike7880d82014-04-30 12:48:25 -0700426 }
427 }
428 return false;
429 }
430
RoboErika5b02322014-05-07 17:05:49 -0700431 private MediaSessionRecord createSessionInternal(int callerPid, int callerUid, int userId,
RoboErik4646d282014-05-13 10:13:04 -0700432 String callerPackageName, ISessionCallback cb, String tag) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800433 synchronized (mLock) {
RoboErika5b02322014-05-07 17:05:49 -0700434 return createSessionLocked(callerPid, callerUid, userId, callerPackageName, cb, tag);
RoboErik01fe6612014-02-13 14:19:04 -0800435 }
436 }
437
RoboErik4646d282014-05-13 10:13:04 -0700438 /*
439 * When a session is created the following things need to happen.
RoboErik8a2cfc32014-05-16 11:19:38 -0700440 * 1. Its callback binder needs a link to death
RoboErik4646d282014-05-13 10:13:04 -0700441 * 2. It needs to be added to all sessions.
442 * 3. It needs to be added to the priority stack.
443 * 4. It needs to be added to the relevant user record.
444 */
RoboErika5b02322014-05-07 17:05:49 -0700445 private MediaSessionRecord createSessionLocked(int callerPid, int callerUid, int userId,
446 String callerPackageName, ISessionCallback cb, String tag) {
RoboErik4646d282014-05-13 10:13:04 -0700447
Dongwon Kang8cf39c52016-07-29 13:20:39 -0700448 UserRecord user = mUserRecords.get(userId);
449 if (user == null) {
450 Log.wtf(TAG, "Request from invalid user: " + userId);
451 throw new RuntimeException("Session request from invalid user.");
452 }
453
RoboErika5b02322014-05-07 17:05:49 -0700454 final MediaSessionRecord session = new MediaSessionRecord(callerPid, callerUid, userId,
455 callerPackageName, cb, tag, this, mHandler);
RoboErik01fe6612014-02-13 14:19:04 -0800456 try {
457 cb.asBinder().linkToDeath(session, 0);
458 } catch (RemoteException e) {
459 throw new RuntimeException("Media Session owner died prematurely.", e);
460 }
RoboErik4646d282014-05-13 10:13:04 -0700461
Jaewan Kim8f729082016-06-21 12:36:26 +0900462 mPriorityStack.addSession(session, mCurrentUserIdList.contains(userId));
RoboErik4646d282014-05-13 10:13:04 -0700463 user.addSessionLocked(session);
464
RoboErik2e7a9162014-06-04 16:53:45 -0700465 mHandler.post(MessageHandler.MSG_SESSIONS_CHANGED, userId, 0);
466
RoboErik01fe6612014-02-13 14:19:04 -0800467 if (DEBUG) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +0900468 Log.d(TAG, "Created session for " + callerPackageName + " with tag " + tag);
RoboErik01fe6612014-02-13 14:19:04 -0800469 }
470 return session;
471 }
472
RoboErik2e7a9162014-06-04 16:53:45 -0700473 private int findIndexOfSessionsListenerLocked(IActiveSessionsListener listener) {
474 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
RoboErika08adb242014-11-21 18:28:18 -0800475 if (mSessionsListeners.get(i).mListener.asBinder() == listener.asBinder()) {
RoboErik2e7a9162014-06-04 16:53:45 -0700476 return i;
477 }
478 }
479 return -1;
480 }
481
RoboErik2e7a9162014-06-04 16:53:45 -0700482 private void pushSessionsChanged(int userId) {
483 synchronized (mLock) {
484 List<MediaSessionRecord> records = mPriorityStack.getActiveSessions(userId);
485 int size = records.size();
RoboErik870c5a62014-12-02 15:08:26 -0800486 if (size > 0 && records.get(0).isPlaybackActive(false)) {
RoboErikb214efb2014-07-24 13:20:30 -0700487 rememberMediaButtonReceiverLocked(records.get(0));
RoboErik6f0e4dd2014-06-17 16:56:27 -0700488 }
Jeff Browndba34ba2014-06-24 20:46:03 -0700489 ArrayList<MediaSession.Token> tokens = new ArrayList<MediaSession.Token>();
RoboErik2e7a9162014-06-04 16:53:45 -0700490 for (int i = 0; i < size; i++) {
Jeff Browndba34ba2014-06-24 20:46:03 -0700491 tokens.add(new MediaSession.Token(records.get(i).getControllerBinder()));
RoboErik2e7a9162014-06-04 16:53:45 -0700492 }
RoboErik19c95182014-06-23 15:38:48 -0700493 pushRemoteVolumeUpdateLocked(userId);
RoboErik2e7a9162014-06-04 16:53:45 -0700494 for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
495 SessionsListenerRecord record = mSessionsListeners.get(i);
496 if (record.mUserId == UserHandle.USER_ALL || record.mUserId == userId) {
497 try {
498 record.mListener.onActiveSessionsChanged(tokens);
499 } catch (RemoteException e) {
500 Log.w(TAG, "Dead ActiveSessionsListener in pushSessionsChanged, removing",
501 e);
502 mSessionsListeners.remove(i);
503 }
504 }
505 }
506 }
507 }
508
RoboErik19c95182014-06-23 15:38:48 -0700509 private void pushRemoteVolumeUpdateLocked(int userId) {
510 if (mRvc != null) {
511 try {
512 MediaSessionRecord record = mPriorityStack.getDefaultRemoteSession(userId);
513 mRvc.updateRemoteController(record == null ? null : record.getControllerBinder());
514 } catch (RemoteException e) {
515 Log.wtf(TAG, "Error sending default remote volume to sys ui.", e);
516 }
517 }
518 }
519
RoboErikb214efb2014-07-24 13:20:30 -0700520 private void rememberMediaButtonReceiverLocked(MediaSessionRecord record) {
521 PendingIntent receiver = record.getMediaButtonReceiver();
522 UserRecord user = mUserRecords.get(record.getUserId());
523 if (receiver != null && user != null) {
524 user.mLastMediaButtonReceiver = receiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800525 ComponentName component = receiver.getIntent().getComponent();
526 if (component != null && record.getPackageName().equals(component.getPackageName())) {
527 Settings.Secure.putStringForUser(mContentResolver,
528 Settings.System.MEDIA_BUTTON_RECEIVER, component.flattenToString(),
529 record.getUserId());
530 }
RoboErik6f0e4dd2014-06-17 16:56:27 -0700531 }
532 }
533
Jaewan Kim50269362016-12-23 11:22:02 +0900534 private String getCallingPackageName(int uid) {
535 String[] packages = getContext().getPackageManager().getPackagesForUid(uid);
536 if (packages != null && packages.length > 0) {
537 return packages[0];
538 }
539 return "";
540 }
541
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900542 private void dispatchVolumeKeyLongPressLocked(KeyEvent keyEvent) {
543 // Only consider full user.
544 UserRecord user = mUserRecords.get(mCurrentUserIdList.get(0));
545 try {
546 user.mOnVolumeKeyLongPressListener.onVolumeKeyLongPress(keyEvent);
547 } catch (RemoteException e) {
548 Log.w(TAG, "Failed to send " + keyEvent + " to volume key long-press listener");
549 }
550 }
551
RoboErik4646d282014-05-13 10:13:04 -0700552 /**
553 * Information about a particular user. The contents of this object is
554 * guarded by mLock.
555 */
556 final class UserRecord {
557 private final int mUserId;
RoboErik4646d282014-05-13 10:13:04 -0700558 private final ArrayList<MediaSessionRecord> mSessions = new ArrayList<MediaSessionRecord>();
RoboErikc8f92d12015-01-05 16:48:07 -0800559 private final Context mContext;
RoboErikb214efb2014-07-24 13:20:30 -0700560 private PendingIntent mLastMediaButtonReceiver;
RoboErikc8f92d12015-01-05 16:48:07 -0800561 private ComponentName mRestoredMediaButtonReceiver;
RoboErik4646d282014-05-13 10:13:04 -0700562
Jaewan Kim50269362016-12-23 11:22:02 +0900563 private IOnVolumeKeyLongPressListener mOnVolumeKeyLongPressListener;
564 private int mOnVolumeKeyLongPressListenerUid;
565 private KeyEvent mInitialDownVolumeKeyEvent;
566 private int mInitialDownVolumeStream;
567 private boolean mInitialDownMusicOnly;
568
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800569 private IOnMediaKeyListener mOnMediaKeyListener;
570 private int mOnMediaKeyListenerUid;
571
RoboErik4646d282014-05-13 10:13:04 -0700572 public UserRecord(Context context, int userId) {
RoboErikc8f92d12015-01-05 16:48:07 -0800573 mContext = context;
RoboErik4646d282014-05-13 10:13:04 -0700574 mUserId = userId;
RoboErikc8f92d12015-01-05 16:48:07 -0800575 restoreMediaButtonReceiver();
RoboErik4646d282014-05-13 10:13:04 -0700576 }
577
RoboErik4646d282014-05-13 10:13:04 -0700578 public void destroyLocked() {
579 for (int i = mSessions.size() - 1; i >= 0; i--) {
580 MediaSessionRecord session = mSessions.get(i);
581 MediaSessionService.this.destroySessionLocked(session);
RoboErik4646d282014-05-13 10:13:04 -0700582 }
583 }
584
RoboErik4646d282014-05-13 10:13:04 -0700585 public ArrayList<MediaSessionRecord> getSessionsLocked() {
586 return mSessions;
587 }
588
589 public void addSessionLocked(MediaSessionRecord session) {
590 mSessions.add(session);
RoboErik4646d282014-05-13 10:13:04 -0700591 }
592
593 public void removeSessionLocked(MediaSessionRecord session) {
594 mSessions.remove(session);
RoboErik4646d282014-05-13 10:13:04 -0700595 }
596
597 public void dumpLocked(PrintWriter pw, String prefix) {
598 pw.println(prefix + "Record for user " + mUserId);
599 String indent = prefix + " ";
RoboErikb214efb2014-07-24 13:20:30 -0700600 pw.println(indent + "MediaButtonReceiver:" + mLastMediaButtonReceiver);
RoboErikc8f92d12015-01-05 16:48:07 -0800601 pw.println(indent + "Restored ButtonReceiver:" + mRestoredMediaButtonReceiver);
Jaewan Kim50269362016-12-23 11:22:02 +0900602 pw.println(indent + "Volume key long-press listener:" + mOnVolumeKeyLongPressListener);
603 pw.println(indent + "Volume key long-press listener package:" +
604 getCallingPackageName(mOnVolumeKeyLongPressListenerUid));
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800605 pw.println(indent + "Media key listener: " + mOnMediaKeyListener);
606 pw.println(indent + "Media key listener package: " +
607 getCallingPackageName(mOnMediaKeyListenerUid));
Jeff Brown01a500e2014-07-10 22:50:50 -0700608 int size = mSessions.size();
RoboErik4646d282014-05-13 10:13:04 -0700609 pw.println(indent + size + " Sessions:");
610 for (int i = 0; i < size; i++) {
RoboErikaa4e23b2014-07-24 18:35:11 -0700611 // Just print the short version, the full session dump will
RoboErik4646d282014-05-13 10:13:04 -0700612 // already be in the list of all sessions.
RoboErikaa4e23b2014-07-24 18:35:11 -0700613 pw.println(indent + mSessions.get(i).toString());
RoboErik4646d282014-05-13 10:13:04 -0700614 }
615 }
RoboErikc8f92d12015-01-05 16:48:07 -0800616
617 private void restoreMediaButtonReceiver() {
618 String receiverName = Settings.Secure.getStringForUser(mContentResolver,
Jaewan Kim8f729082016-06-21 12:36:26 +0900619 Settings.System.MEDIA_BUTTON_RECEIVER, mUserId);
RoboErikc8f92d12015-01-05 16:48:07 -0800620 if (!TextUtils.isEmpty(receiverName)) {
621 ComponentName eventReceiver = ComponentName.unflattenFromString(receiverName);
622 if (eventReceiver == null) {
623 // an invalid name was persisted
624 return;
625 }
626 mRestoredMediaButtonReceiver = eventReceiver;
627 }
628 }
RoboErik4646d282014-05-13 10:13:04 -0700629 }
630
RoboErik2e7a9162014-06-04 16:53:45 -0700631 final class SessionsListenerRecord implements IBinder.DeathRecipient {
632 private final IActiveSessionsListener mListener;
RoboErik7aef77b2014-08-08 15:56:54 -0700633 private final ComponentName mComponentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700634 private final int mUserId;
RoboErik7aef77b2014-08-08 15:56:54 -0700635 private final int mPid;
636 private final int mUid;
RoboErik2e7a9162014-06-04 16:53:45 -0700637
RoboErik7aef77b2014-08-08 15:56:54 -0700638 public SessionsListenerRecord(IActiveSessionsListener listener,
639 ComponentName componentName,
640 int userId, int pid, int uid) {
RoboErik2e7a9162014-06-04 16:53:45 -0700641 mListener = listener;
RoboErik7aef77b2014-08-08 15:56:54 -0700642 mComponentName = componentName;
RoboErik2e7a9162014-06-04 16:53:45 -0700643 mUserId = userId;
RoboErik7aef77b2014-08-08 15:56:54 -0700644 mPid = pid;
645 mUid = uid;
RoboErik2e7a9162014-06-04 16:53:45 -0700646 }
647
648 @Override
649 public void binderDied() {
650 synchronized (mLock) {
651 mSessionsListeners.remove(this);
652 }
653 }
654 }
655
RoboErik7aef77b2014-08-08 15:56:54 -0700656 final class SettingsObserver extends ContentObserver {
657 private final Uri mSecureSettingsUri = Settings.Secure.getUriFor(
658 Settings.Secure.ENABLED_NOTIFICATION_LISTENERS);
659
660 private SettingsObserver() {
661 super(null);
662 }
663
664 private void observe() {
665 mContentResolver.registerContentObserver(mSecureSettingsUri,
666 false, this, UserHandle.USER_ALL);
667 }
668
669 @Override
670 public void onChange(boolean selfChange, Uri uri) {
671 updateActiveSessionListeners();
672 }
673 }
674
RoboErik07c70772014-03-20 13:33:52 -0700675 class SessionManagerImpl extends ISessionManager.Stub {
RoboErik8a2cfc32014-05-16 11:19:38 -0700676 private static final String EXTRA_WAKELOCK_ACQUIRED =
677 "android.media.AudioService.WAKELOCK_ACQUIRED";
678 private static final int WAKELOCK_RELEASE_ON_FINISHED = 1980; // magic number
679
RoboErik9a9d0b52014-05-20 14:53:39 -0700680 private boolean mVoiceButtonDown = false;
681 private boolean mVoiceButtonHandled = false;
682
RoboErik07c70772014-03-20 13:33:52 -0700683 @Override
RoboErika5b02322014-05-07 17:05:49 -0700684 public ISession createSession(String packageName, ISessionCallback cb, String tag,
685 int userId) throws RemoteException {
RoboErik01fe6612014-02-13 14:19:04 -0800686 final int pid = Binder.getCallingPid();
687 final int uid = Binder.getCallingUid();
688 final long token = Binder.clearCallingIdentity();
689 try {
690 enforcePackageName(packageName, uid);
RoboErika5b02322014-05-07 17:05:49 -0700691 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
692 false /* allowAll */, true /* requireFull */, "createSession", packageName);
RoboErik01fe6612014-02-13 14:19:04 -0800693 if (cb == null) {
694 throw new IllegalArgumentException("Controller callback cannot be null");
695 }
RoboErika5b02322014-05-07 17:05:49 -0700696 return createSessionInternal(pid, uid, resolvedUserId, packageName, cb, tag)
697 .getSessionBinder();
RoboErike7880d82014-04-30 12:48:25 -0700698 } finally {
699 Binder.restoreCallingIdentity(token);
700 }
701 }
702
703 @Override
RoboErika5b02322014-05-07 17:05:49 -0700704 public List<IBinder> getSessions(ComponentName componentName, int userId) {
RoboErike7880d82014-04-30 12:48:25 -0700705 final int pid = Binder.getCallingPid();
706 final int uid = Binder.getCallingUid();
707 final long token = Binder.clearCallingIdentity();
708
709 try {
RoboErik2e7a9162014-06-04 16:53:45 -0700710 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
RoboErike7880d82014-04-30 12:48:25 -0700711 ArrayList<IBinder> binders = new ArrayList<IBinder>();
712 synchronized (mLock) {
RoboErika8f95142014-05-05 14:23:49 -0700713 ArrayList<MediaSessionRecord> records = mPriorityStack
RoboErika5b02322014-05-07 17:05:49 -0700714 .getActiveSessions(resolvedUserId);
RoboErika8f95142014-05-05 14:23:49 -0700715 int size = records.size();
716 for (int i = 0; i < size; i++) {
717 binders.add(records.get(i).getControllerBinder().asBinder());
RoboErike7880d82014-04-30 12:48:25 -0700718 }
719 }
720 return binders;
RoboErik01fe6612014-02-13 14:19:04 -0800721 } finally {
722 Binder.restoreCallingIdentity(token);
723 }
724 }
RoboErika278ea72014-04-24 14:49:01 -0700725
RoboErik2e7a9162014-06-04 16:53:45 -0700726 @Override
727 public void addSessionsListener(IActiveSessionsListener listener,
728 ComponentName componentName, int userId) throws RemoteException {
729 final int pid = Binder.getCallingPid();
730 final int uid = Binder.getCallingUid();
731 final long token = Binder.clearCallingIdentity();
732
733 try {
734 int resolvedUserId = verifySessionsRequest(componentName, userId, pid, uid);
735 synchronized (mLock) {
736 int index = findIndexOfSessionsListenerLocked(listener);
737 if (index != -1) {
738 Log.w(TAG, "ActiveSessionsListener is already added, ignoring");
739 return;
740 }
741 SessionsListenerRecord record = new SessionsListenerRecord(listener,
RoboErik7aef77b2014-08-08 15:56:54 -0700742 componentName, resolvedUserId, pid, uid);
RoboErik2e7a9162014-06-04 16:53:45 -0700743 try {
744 listener.asBinder().linkToDeath(record, 0);
745 } catch (RemoteException e) {
746 Log.e(TAG, "ActiveSessionsListener is dead, ignoring it", e);
747 return;
748 }
749 mSessionsListeners.add(record);
750 }
751 } finally {
752 Binder.restoreCallingIdentity(token);
753 }
754 }
755
756 @Override
757 public void removeSessionsListener(IActiveSessionsListener listener)
758 throws RemoteException {
759 synchronized (mLock) {
760 int index = findIndexOfSessionsListenerLocked(listener);
761 if (index != -1) {
762 SessionsListenerRecord record = mSessionsListeners.remove(index);
763 try {
764 record.mListener.asBinder().unlinkToDeath(record, 0);
765 } catch (Exception e) {
766 // ignore exceptions, the record is being removed
767 }
768 }
769 }
770 }
771
RoboErik8a2cfc32014-05-16 11:19:38 -0700772 /**
773 * Handles the dispatching of the media button events to one of the
774 * registered listeners, or if there was none, broadcast an
775 * ACTION_MEDIA_BUTTON intent to the rest of the system.
776 *
777 * @param keyEvent a non-null KeyEvent whose key code is one of the
778 * supported media buttons
779 * @param needWakeLock true if a PARTIAL_WAKE_LOCK needs to be held
780 * while this key event is dispatched.
781 */
782 @Override
783 public void dispatchMediaKeyEvent(KeyEvent keyEvent, boolean needWakeLock) {
784 if (keyEvent == null || !KeyEvent.isMediaKey(keyEvent.getKeyCode())) {
785 Log.w(TAG, "Attempted to dispatch null or non-media key event.");
786 return;
787 }
Jeff Brown38d3feb2015-03-19 18:26:30 -0700788
RoboErik8a2cfc32014-05-16 11:19:38 -0700789 final int pid = Binder.getCallingPid();
790 final int uid = Binder.getCallingUid();
791 final long token = Binder.clearCallingIdentity();
RoboErik8a2cfc32014-05-16 11:19:38 -0700792 try {
Jeff Brown221a8272015-03-23 13:53:09 -0700793 if (DEBUG) {
794 Log.d(TAG, "dispatchMediaKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
795 + keyEvent);
796 }
Jeff Brown38d3feb2015-03-19 18:26:30 -0700797 if (!isUserSetupComplete()) {
798 // Global media key handling can have the side-effect of starting new
799 // activities which is undesirable while setup is in progress.
800 Slog.i(TAG, "Not dispatching media key event because user "
801 + "setup is in progress.");
802 return;
803 }
804
RoboErik8a2cfc32014-05-16 11:19:38 -0700805 synchronized (mLock) {
Jaewan Kim51255012017-02-24 16:19:14 +0900806 boolean isGlobalPriorityActive = mPriorityStack.isGlobalPriorityActive();
807 if (isGlobalPriorityActive && uid != Process.SYSTEM_UID) {
808 // Prevent dispatching key event through reflection while the global
809 // priority session is active.
810 Slog.i(TAG, "Only the system can dispatch media key event "
811 + "to the global priority session.");
812 return;
813 }
814 if (!isGlobalPriorityActive && isVoiceKey(keyEvent.getKeyCode())) {
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800815 handleVoiceKeyEventLocked(keyEvent, needWakeLock);
RoboErik8a2cfc32014-05-16 11:19:38 -0700816 } else {
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800817 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, true);
RoboErik8a2cfc32014-05-16 11:19:38 -0700818 }
819 }
820 } finally {
821 Binder.restoreCallingIdentity(token);
822 }
823 }
824
RoboErika278ea72014-04-24 14:49:01 -0700825 @Override
Jaewan Kim50269362016-12-23 11:22:02 +0900826 public void setOnVolumeKeyLongPressListener(IOnVolumeKeyLongPressListener listener) {
827 final int pid = Binder.getCallingPid();
828 final int uid = Binder.getCallingUid();
829 final long token = Binder.clearCallingIdentity();
830 try {
831 // Enforce SET_VOLUME_KEY_LONG_PRESS_LISTENER permission.
832 if (getContext().checkPermission(
833 android.Manifest.permission.SET_VOLUME_KEY_LONG_PRESS_LISTENER, pid, uid)
834 != PackageManager.PERMISSION_GRANTED) {
835 throw new SecurityException("Must hold the SET_VOLUME_KEY_LONG_PRESS_LISTENER" +
836 " permission.");
837 }
838
839 synchronized (mLock) {
840 UserRecord user = mUserRecords.get(UserHandle.getUserId(uid));
841 if (user.mOnVolumeKeyLongPressListener != null &&
842 user.mOnVolumeKeyLongPressListenerUid != uid) {
843 Log.w(TAG, "Volume key long-press listener cannot be reset by another app");
844 return;
845 }
846
847 user.mOnVolumeKeyLongPressListener = listener;
848 user.mOnVolumeKeyLongPressListenerUid = uid;
849
850 Log.d(TAG, "Volume key long-press listener "
851 + listener + " is set by " + getCallingPackageName(uid));
852
853 if (user.mOnVolumeKeyLongPressListener != null) {
854 try {
855 user.mOnVolumeKeyLongPressListener.asBinder().linkToDeath(
856 new IBinder.DeathRecipient() {
857 @Override
858 public void binderDied() {
859 synchronized (mLock) {
860 user.mOnVolumeKeyLongPressListener = null;
861 }
862 }
863 }, 0);
864 } catch (RemoteException e) {
865 Log.w(TAG, "Failed to set death recipient "
866 + user.mOnVolumeKeyLongPressListener);
867 user.mOnVolumeKeyLongPressListener = null;
868 }
869 }
870 }
871 } finally {
872 Binder.restoreCallingIdentity(token);
873 }
874 }
875
Jaewan Kim6e2b01c2017-01-19 16:33:14 -0800876 @Override
877 public void setOnMediaKeyListener(IOnMediaKeyListener listener) {
878 final int pid = Binder.getCallingPid();
879 final int uid = Binder.getCallingUid();
880 final long token = Binder.clearCallingIdentity();
881 try {
882 // Enforce SET_MEDIA_KEY_LISTENER permission.
883 if (getContext().checkPermission(
884 android.Manifest.permission.SET_MEDIA_KEY_LISTENER, pid, uid)
885 != PackageManager.PERMISSION_GRANTED) {
886 throw new SecurityException("Must hold the SET_MEDIA_KEY_LISTENER" +
887 " permission.");
888 }
889
890 synchronized (mLock) {
891 int userId = UserHandle.getUserId(uid);
892 UserRecord user = mUserRecords.get(userId);
893 if (user.mOnMediaKeyListener != null && user.mOnMediaKeyListenerUid != uid) {
894 Log.w(TAG, "Media key listener cannot be reset by another app");
895 return;
896 }
897
898 user.mOnMediaKeyListener = listener;
899 user.mOnMediaKeyListenerUid = uid;
900
901 Log.d(TAG, "Media key listener " + user.mOnMediaKeyListener
902 + " is set by " + getCallingPackageName(uid));
903
904 if (user.mOnMediaKeyListener != null) {
905 try {
906 user.mOnMediaKeyListener.asBinder().linkToDeath(
907 new IBinder.DeathRecipient() {
908 @Override
909 public void binderDied() {
910 synchronized (mLock) {
911 user.mOnMediaKeyListener = null;
912 }
913 }
914 }, 0);
915 } catch (RemoteException e) {
916 Log.w(TAG, "Failed to set death recipient " + user.mOnMediaKeyListener);
917 user.mOnMediaKeyListener = null;
918 }
919 }
920 }
921 } finally {
922 Binder.restoreCallingIdentity(token);
923 }
924 }
925
Jaewan Kim50269362016-12-23 11:22:02 +0900926 /**
927 * Handles the dispatching of the volume button events to one of the
928 * registered listeners. If there's a volume key long-press listener and
929 * there's no active global priority session, long-pressess will be sent to the
930 * long-press listener instead of adjusting volume.
931 *
932 * @param keyEvent a non-null KeyEvent whose key code is one of the
933 * {@link KeyEvent#KEYCODE_VOLUME_UP},
934 * {@link KeyEvent#KEYCODE_VOLUME_DOWN},
935 * or {@link KeyEvent#KEYCODE_VOLUME_MUTE}.
936 * @param stream stream type to adjust volume.
937 * @param musicOnly true if both UI nor haptic feedback aren't needed when adjust volume.
938 */
939 @Override
940 public void dispatchVolumeKeyEvent(KeyEvent keyEvent, int stream, boolean musicOnly) {
941 if (keyEvent == null ||
942 (keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_UP
943 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_DOWN
944 && keyEvent.getKeyCode() != KeyEvent.KEYCODE_VOLUME_MUTE)) {
945 Log.w(TAG, "Attempted to dispatch null or non-volume key event.");
946 return;
947 }
948
949 final int pid = Binder.getCallingPid();
950 final int uid = Binder.getCallingUid();
951 final long token = Binder.clearCallingIdentity();
952
953 if (DEBUG) {
954 Log.d(TAG, "dispatchVolumeKeyEvent, pid=" + pid + ", uid=" + uid + ", event="
955 + keyEvent);
956 }
957
958 try {
959 synchronized (mLock) {
960 // Only consider full user.
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900961 int userId = mCurrentUserIdList.get(0);
962 UserRecord user = mUserRecords.get(userId);
Jaewan Kim50269362016-12-23 11:22:02 +0900963
964 if (mPriorityStack.isGlobalPriorityActive()
965 || user.mOnVolumeKeyLongPressListener == null) {
966 dispatchVolumeKeyEventLocked(keyEvent, stream, musicOnly);
967 } else {
968 // TODO: Consider the case when both volume up and down keys are pressed
969 // at the same time.
970 if (keyEvent.getAction() == KeyEvent.ACTION_DOWN) {
971 if (keyEvent.getRepeatCount() == 0) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900972 // Keeps the copy of the KeyEvent because it can be reused.
973 user.mInitialDownVolumeKeyEvent = KeyEvent.obtain(keyEvent);
Jaewan Kim50269362016-12-23 11:22:02 +0900974 user.mInitialDownVolumeStream = stream;
975 user.mInitialDownMusicOnly = musicOnly;
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900976 mHandler.sendMessageDelayed(
977 mHandler.obtainMessage(
978 MessageHandler.MSG_VOLUME_INITIAL_DOWN, userId, 0),
979 mLongPressTimeout);
Jaewan Kim50269362016-12-23 11:22:02 +0900980 }
981 if (keyEvent.getRepeatCount() > 0 || keyEvent.isLongPress()) {
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900982 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kim50269362016-12-23 11:22:02 +0900983 if (user.mInitialDownVolumeKeyEvent != null) {
984 dispatchVolumeKeyLongPressLocked(
985 user.mInitialDownVolumeKeyEvent);
986 // Mark that the key is already handled.
987 user.mInitialDownVolumeKeyEvent = null;
988 }
989 dispatchVolumeKeyLongPressLocked(keyEvent);
990 }
991 } else { // if up
Jaewan Kimd61a87b2017-02-17 23:14:10 +0900992 mHandler.removeMessages(MessageHandler.MSG_VOLUME_INITIAL_DOWN);
Jaewan Kim50269362016-12-23 11:22:02 +0900993 if (user.mInitialDownVolumeKeyEvent != null
994 && user.mInitialDownVolumeKeyEvent.getDownTime()
995 == keyEvent.getDownTime()) {
996 // Short-press. Should change volume.
997 dispatchVolumeKeyEventLocked(
998 user.mInitialDownVolumeKeyEvent,
999 user.mInitialDownVolumeStream,
1000 user.mInitialDownMusicOnly);
1001 dispatchVolumeKeyEventLocked(keyEvent, stream, musicOnly);
1002 } else {
1003 dispatchVolumeKeyLongPressLocked(keyEvent);
1004 }
1005 }
1006 }
1007 }
1008 } finally {
1009 Binder.restoreCallingIdentity(token);
1010 }
1011 }
1012
Jaewan Kim50269362016-12-23 11:22:02 +09001013 private void dispatchVolumeKeyEventLocked(
1014 KeyEvent keyEvent, int stream, boolean musicOnly) {
1015 boolean down = keyEvent.getAction() == KeyEvent.ACTION_DOWN;
1016 boolean up = keyEvent.getAction() == KeyEvent.ACTION_UP;
1017 int direction = 0;
1018 boolean isMute = false;
1019 switch (keyEvent.getKeyCode()) {
1020 case KeyEvent.KEYCODE_VOLUME_UP:
1021 direction = AudioManager.ADJUST_RAISE;
1022 break;
1023 case KeyEvent.KEYCODE_VOLUME_DOWN:
1024 direction = AudioManager.ADJUST_LOWER;
1025 break;
1026 case KeyEvent.KEYCODE_VOLUME_MUTE:
1027 isMute = true;
1028 break;
1029 }
1030 if (down || up) {
1031 int flags = AudioManager.FLAG_FROM_KEY;
1032 if (musicOnly) {
1033 // This flag is used when the screen is off to only affect active media.
1034 flags |= AudioManager.FLAG_ACTIVE_MEDIA_ONLY;
1035 } else {
1036 // These flags are consistent with the home screen
1037 if (up) {
1038 flags |= AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_VIBRATE;
1039 } else {
1040 flags |= AudioManager.FLAG_SHOW_UI | AudioManager.FLAG_VIBRATE;
1041 }
1042 }
1043 if (direction != 0) {
1044 // If this is action up we want to send a beep for non-music events
1045 if (up) {
1046 direction = 0;
1047 }
1048 dispatchAdjustVolumeLocked(stream, direction, flags);
1049 } else if (isMute) {
1050 if (down && keyEvent.getRepeatCount() == 0) {
1051 dispatchAdjustVolumeLocked(stream, AudioManager.ADJUST_TOGGLE_MUTE, flags);
1052 }
1053 }
1054 }
1055 }
1056
1057 @Override
RoboErik7c82ced2014-12-04 17:39:08 -08001058 public void dispatchAdjustVolume(int suggestedStream, int delta, int flags) {
RoboErikb69ffd42014-05-30 14:57:59 -07001059 final long token = Binder.clearCallingIdentity();
1060 try {
1061 synchronized (mLock) {
Jaewan Kim50269362016-12-23 11:22:02 +09001062 dispatchAdjustVolumeLocked(suggestedStream, delta, flags);
RoboErikb69ffd42014-05-30 14:57:59 -07001063 }
1064 } finally {
1065 Binder.restoreCallingIdentity(token);
1066 }
1067 }
1068
1069 @Override
RoboErik19c95182014-06-23 15:38:48 -07001070 public void setRemoteVolumeController(IRemoteVolumeController rvc) {
1071 final int pid = Binder.getCallingPid();
1072 final int uid = Binder.getCallingUid();
1073 final long token = Binder.clearCallingIdentity();
1074 try {
John Spurlockeb69e242015-02-17 17:15:04 -05001075 enforceSystemUiPermission("listen for volume changes", pid, uid);
RoboErik19c95182014-06-23 15:38:48 -07001076 mRvc = rvc;
1077 } finally {
1078 Binder.restoreCallingIdentity(token);
1079 }
1080 }
1081
1082 @Override
RoboErikde9ba392014-09-26 12:51:01 -07001083 public boolean isGlobalPriorityActive() {
Jaewan Kim51255012017-02-24 16:19:14 +09001084 synchronized (mLock) {
1085 return mPriorityStack.isGlobalPriorityActive();
1086 }
RoboErikde9ba392014-09-26 12:51:01 -07001087 }
1088
1089 @Override
RoboErika278ea72014-04-24 14:49:01 -07001090 public void dump(FileDescriptor fd, final PrintWriter pw, String[] args) {
1091 if (getContext().checkCallingOrSelfPermission(Manifest.permission.DUMP)
1092 != PackageManager.PERMISSION_GRANTED) {
1093 pw.println("Permission Denial: can't dump MediaSessionService from from pid="
1094 + Binder.getCallingPid()
1095 + ", uid=" + Binder.getCallingUid());
1096 return;
1097 }
1098
1099 pw.println("MEDIA SESSION SERVICE (dumpsys media_session)");
1100 pw.println();
1101
1102 synchronized (mLock) {
RoboErika08adb242014-11-21 18:28:18 -08001103 pw.println(mSessionsListeners.size() + " sessions listeners.");
RoboErika5b02322014-05-07 17:05:49 -07001104 mPriorityStack.dump(pw, "");
RoboErika8f95142014-05-05 14:23:49 -07001105
RoboErik4646d282014-05-13 10:13:04 -07001106 pw.println("User Records:");
Jaewan Kime0ca3f32017-02-16 15:52:39 +09001107 int count = mUserRecords.size();
RoboErika278ea72014-04-24 14:49:01 -07001108 for (int i = 0; i < count; i++) {
RoboErik7b3da2d2015-02-02 15:21:29 -08001109 UserRecord user = mUserRecords.get(mUserRecords.keyAt(i));
RoboErik4646d282014-05-13 10:13:04 -07001110 user.dumpLocked(pw, "");
RoboErika278ea72014-04-24 14:49:01 -07001111 }
1112 }
1113 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001114
RoboErik2e7a9162014-06-04 16:53:45 -07001115 private int verifySessionsRequest(ComponentName componentName, int userId, final int pid,
1116 final int uid) {
1117 String packageName = null;
1118 if (componentName != null) {
1119 // If they gave us a component name verify they own the
1120 // package
1121 packageName = componentName.getPackageName();
1122 enforcePackageName(packageName, uid);
1123 }
1124 // Check that they can make calls on behalf of the user and
1125 // get the final user id
1126 int resolvedUserId = ActivityManager.handleIncomingUser(pid, uid, userId,
1127 true /* allowAll */, true /* requireFull */, "getSessions", packageName);
1128 // Check if they have the permissions or their component is
1129 // enabled for the user they're calling from.
1130 enforceMediaPermissions(componentName, pid, uid, resolvedUserId);
1131 return resolvedUserId;
1132 }
1133
Jaewan Kim50269362016-12-23 11:22:02 +09001134 private void dispatchAdjustVolumeLocked(int suggestedStream, int direction, int flags) {
1135 MediaSessionRecord session = mPriorityStack.getDefaultVolumeSession(mCurrentUserIdList);
1136
RoboErik9c785402014-11-11 16:52:26 -08001137 boolean preferSuggestedStream = false;
1138 if (isValidLocalStreamType(suggestedStream)
1139 && AudioSystem.isStreamActive(suggestedStream, 0)) {
1140 preferSuggestedStream = true;
1141 }
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001142 if (DEBUG) {
1143 Log.d(TAG, "Adjusting " + session + " by " + direction + ". flags="
1144 + flags + ", suggestedStream=" + suggestedStream
1145 + ", preferSuggestedStream=" + preferSuggestedStream);
1146 }
RoboErik9c785402014-11-11 16:52:26 -08001147 if (session == null || preferSuggestedStream) {
RoboErik94c716e2014-09-14 13:54:31 -07001148 if ((flags & AudioManager.FLAG_ACTIVE_MEDIA_ONLY) != 0
1149 && !AudioSystem.isStreamActive(AudioManager.STREAM_MUSIC, 0)) {
RoboErik3c45c292014-07-08 16:47:31 -07001150 if (DEBUG) {
1151 Log.d(TAG, "No active session to adjust, skipping media only volume event");
RoboErik3c45c292014-07-08 16:47:31 -07001152 }
RoboErikb7c014c2014-07-22 15:58:22 -07001153 return;
RoboErik3c45c292014-07-08 16:47:31 -07001154 }
Shibin George19e84042016-06-14 20:42:13 +05301155
1156 // Execute mAudioService.adjustSuggestedStreamVolume() on
1157 // handler thread of MediaSessionService.
1158 // This will release the MediaSessionService.mLock sooner and avoid
1159 // a potential deadlock between MediaSessionService.mLock and
1160 // ActivityManagerService lock.
1161 mHandler.post(new Runnable() {
1162 @Override
1163 public void run() {
1164 try {
1165 String packageName = getContext().getOpPackageName();
1166 mAudioService.adjustSuggestedStreamVolume(direction, suggestedStream,
1167 flags, packageName, TAG);
1168 } catch (RemoteException e) {
1169 Log.e(TAG, "Error adjusting default volume.", e);
1170 }
1171 }
1172 });
RoboErikb69ffd42014-05-30 14:57:59 -07001173 } else {
RoboErik0dac35a2014-08-12 15:48:49 -07001174 session.adjustVolume(direction, flags, getContext().getPackageName(),
Jaewan Kim8f729082016-06-21 12:36:26 +09001175 Process.SYSTEM_UID, true);
RoboErikb69ffd42014-05-30 14:57:59 -07001176 }
1177 }
1178
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001179 private void handleVoiceKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock) {
RoboErik9a9d0b52014-05-20 14:53:39 -07001180 int action = keyEvent.getAction();
1181 boolean isLongPress = (keyEvent.getFlags() & KeyEvent.FLAG_LONG_PRESS) != 0;
1182 if (action == KeyEvent.ACTION_DOWN) {
1183 if (keyEvent.getRepeatCount() == 0) {
1184 mVoiceButtonDown = true;
1185 mVoiceButtonHandled = false;
1186 } else if (mVoiceButtonDown && !mVoiceButtonHandled && isLongPress) {
1187 mVoiceButtonHandled = true;
1188 startVoiceInput(needWakeLock);
1189 }
1190 } else if (action == KeyEvent.ACTION_UP) {
1191 if (mVoiceButtonDown) {
1192 mVoiceButtonDown = false;
1193 if (!mVoiceButtonHandled && !keyEvent.isCanceled()) {
1194 // Resend the down then send this event through
1195 KeyEvent downEvent = KeyEvent.changeAction(keyEvent, KeyEvent.ACTION_DOWN);
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001196 dispatchMediaKeyEventLocked(downEvent, needWakeLock, true);
1197 dispatchMediaKeyEventLocked(keyEvent, needWakeLock, true);
RoboErik9a9d0b52014-05-20 14:53:39 -07001198 }
1199 }
1200 }
1201 }
1202
1203 private void dispatchMediaKeyEventLocked(KeyEvent keyEvent, boolean needWakeLock,
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001204 boolean checkMediaKeyListener) {
1205 // If we don't have a media button receiver to fall back on
1206 // include non-playing sessions for dispatching.
1207 boolean useNotPlayingSessions = true;
1208 for (int userId : mCurrentUserIdList) {
1209 UserRecord ur = mUserRecords.get(userId);
1210 if (ur.mLastMediaButtonReceiver != null
1211 || ur.mRestoredMediaButtonReceiver != null) {
1212 useNotPlayingSessions = false;
1213 break;
1214 }
1215 }
1216 if (DEBUG) {
1217 Log.d(TAG, "dispatchMediaKeyEvent, useNotPlayingSessions="
1218 + useNotPlayingSessions);
1219 }
1220
1221 MediaSessionRecord session = mPriorityStack.getDefaultMediaButtonSession(
1222 mCurrentUserIdList, useNotPlayingSessions);
1223
1224 if ((session == null
1225 || !session.hasFlag(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY))
1226 && checkMediaKeyListener) {
1227 // Only consider full user.
1228 UserRecord user = mUserRecords.get(mCurrentUserIdList.get(0));
1229 if (user.mOnMediaKeyListener != null) {
1230 if (DEBUG_KEY_EVENT) {
1231 Log.d(TAG, "Send " + keyEvent + " to media key listener");
1232 }
1233 try {
1234 user.mOnMediaKeyListener.onMediaKey(keyEvent,
1235 new MediaKeyListenerResultReceiver(keyEvent, needWakeLock));
1236 return;
1237 } catch (RemoteException e) {
1238 Log.w(TAG, "Failed to send " + keyEvent + " to media key listener");
1239 }
1240 }
1241 }
RoboErik9a9d0b52014-05-20 14:53:39 -07001242 if (session != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001243 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001244 Log.d(TAG, "Sending " + keyEvent + " to " + session);
RoboErik9a9d0b52014-05-20 14:53:39 -07001245 }
1246 if (needWakeLock) {
1247 mKeyEventReceiver.aquireWakeLockLocked();
1248 }
Jaewan Kim50269362016-12-23 11:22:02 +09001249 // If we don't need a wakelock use -1 as the id so we won't release it later.
RoboErik9a9d0b52014-05-20 14:53:39 -07001250 session.sendMediaButton(keyEvent,
1251 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
Jaewan Kim8f729082016-06-21 12:36:26 +09001252 mKeyEventReceiver, Process.SYSTEM_UID,
Donghyun Cho1ea56832016-02-23 16:30:07 +09001253 getContext().getPackageName());
RoboErik9a9d0b52014-05-20 14:53:39 -07001254 } else {
RoboErikb214efb2014-07-24 13:20:30 -07001255 // Launch the last PendingIntent we had with priority
Jaewan Kim8f729082016-06-21 12:36:26 +09001256 for (int userId : mCurrentUserIdList) {
1257 UserRecord user = mUserRecords.get(userId);
1258 if (user.mLastMediaButtonReceiver == null
1259 && user.mRestoredMediaButtonReceiver == null) {
1260 continue;
1261 }
RoboErikb214efb2014-07-24 13:20:30 -07001262 if (needWakeLock) {
1263 mKeyEventReceiver.aquireWakeLockLocked();
1264 }
1265 Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
Insun Kang2054db32016-04-07 15:34:34 +09001266 mediaButtonIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
RoboErikb214efb2014-07-24 13:20:30 -07001267 mediaButtonIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
1268 try {
RoboErikc8f92d12015-01-05 16:48:07 -08001269 if (user.mLastMediaButtonReceiver != null) {
Jaewan Kim50269362016-12-23 11:22:02 +09001270 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001271 Log.d(TAG, "Sending " + keyEvent
1272 + " to the last known pendingIntent "
1273 + user.mLastMediaButtonReceiver);
1274 }
RoboErikc8f92d12015-01-05 16:48:07 -08001275 user.mLastMediaButtonReceiver.send(getContext(),
1276 needWakeLock ? mKeyEventReceiver.mLastTimeoutId : -1,
riddle_hsu02ed0122015-10-20 16:00:15 +08001277 mediaButtonIntent, mKeyEventReceiver, mHandler);
RoboErikc8f92d12015-01-05 16:48:07 -08001278 } else {
Jaewan Kim50269362016-12-23 11:22:02 +09001279 if (DEBUG_KEY_EVENT) {
Jaewan Kim5e1476e2016-07-19 22:25:39 +09001280 Log.d(TAG, "Sending " + keyEvent + " to the restored intent "
1281 + user.mRestoredMediaButtonReceiver);
1282 }
RoboErikc8f92d12015-01-05 16:48:07 -08001283 mediaButtonIntent.setComponent(user.mRestoredMediaButtonReceiver);
1284 getContext().sendBroadcastAsUser(mediaButtonIntent,
Jaewan Kim8f729082016-06-21 12:36:26 +09001285 UserHandle.of(userId));
RoboErikc8f92d12015-01-05 16:48:07 -08001286 }
RoboErikb214efb2014-07-24 13:20:30 -07001287 } catch (CanceledException e) {
1288 Log.i(TAG, "Error sending key event to media button receiver "
1289 + user.mLastMediaButtonReceiver, e);
1290 }
Jaewan Kim8f729082016-06-21 12:36:26 +09001291 return;
RoboErik9a9d0b52014-05-20 14:53:39 -07001292 }
Jaewan Kim8f729082016-06-21 12:36:26 +09001293 if (DEBUG) {
1294 Log.d(TAG, "Sending media key ordered broadcast");
1295 }
1296 if (needWakeLock) {
1297 mMediaEventWakeLock.acquire();
1298 }
1299 // Fallback to legacy behavior
1300 Intent keyIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
1301 keyIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
1302 keyIntent.putExtra(Intent.EXTRA_KEY_EVENT, keyEvent);
1303 if (needWakeLock) {
1304 keyIntent.putExtra(EXTRA_WAKELOCK_ACQUIRED, WAKELOCK_RELEASE_ON_FINISHED);
1305 }
1306 // Send broadcast only to the full user.
1307 getContext().sendOrderedBroadcastAsUser(keyIntent, UserHandle.CURRENT,
1308 null, mKeyEventDone, mHandler, Activity.RESULT_OK, null, null);
RoboErik9a9d0b52014-05-20 14:53:39 -07001309 }
1310 }
1311
1312 private void startVoiceInput(boolean needWakeLock) {
1313 Intent voiceIntent = null;
1314 // select which type of search to launch:
1315 // - screen on and device unlocked: action is ACTION_WEB_SEARCH
1316 // - device locked or screen off: action is
1317 // ACTION_VOICE_SEARCH_HANDS_FREE
1318 // with EXTRA_SECURE set to true if the device is securely locked
1319 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
1320 boolean isLocked = mKeyguardManager != null && mKeyguardManager.isKeyguardLocked();
1321 if (!isLocked && pm.isScreenOn()) {
1322 voiceIntent = new Intent(android.speech.RecognizerIntent.ACTION_WEB_SEARCH);
1323 Log.i(TAG, "voice-based interactions: about to use ACTION_WEB_SEARCH");
1324 } else {
1325 voiceIntent = new Intent(RecognizerIntent.ACTION_VOICE_SEARCH_HANDS_FREE);
1326 voiceIntent.putExtra(RecognizerIntent.EXTRA_SECURE,
1327 isLocked && mKeyguardManager.isKeyguardSecure());
1328 Log.i(TAG, "voice-based interactions: about to use ACTION_VOICE_SEARCH_HANDS_FREE");
1329 }
1330 // start the search activity
1331 if (needWakeLock) {
1332 mMediaEventWakeLock.acquire();
1333 }
1334 try {
1335 if (voiceIntent != null) {
1336 voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1337 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
Jaewan Kim8f729082016-06-21 12:36:26 +09001338 if (DEBUG) Log.d(TAG, "voiceIntent: " + voiceIntent);
RoboErik9a9d0b52014-05-20 14:53:39 -07001339 getContext().startActivityAsUser(voiceIntent, UserHandle.CURRENT);
1340 }
1341 } catch (ActivityNotFoundException e) {
1342 Log.w(TAG, "No activity for search: " + e);
1343 } finally {
1344 if (needWakeLock) {
1345 mMediaEventWakeLock.release();
1346 }
1347 }
1348 }
1349
1350 private boolean isVoiceKey(int keyCode) {
1351 return keyCode == KeyEvent.KEYCODE_HEADSETHOOK;
1352 }
1353
Jeff Brown38d3feb2015-03-19 18:26:30 -07001354 private boolean isUserSetupComplete() {
1355 return Settings.Secure.getIntForUser(getContext().getContentResolver(),
1356 Settings.Secure.USER_SETUP_COMPLETE, 0, UserHandle.USER_CURRENT) != 0;
1357 }
1358
RoboErik9c785402014-11-11 16:52:26 -08001359 // we only handle public stream types, which are 0-5
1360 private boolean isValidLocalStreamType(int streamType) {
1361 return streamType >= AudioManager.STREAM_VOICE_CALL
1362 && streamType <= AudioManager.STREAM_NOTIFICATION;
1363 }
1364
Jaewan Kim6e2b01c2017-01-19 16:33:14 -08001365 private class MediaKeyListenerResultReceiver extends ResultReceiver implements Runnable {
1366 private KeyEvent mKeyEvent;
1367 private boolean mNeedWakeLock;
1368 private boolean mHandled;
1369
1370 private MediaKeyListenerResultReceiver(KeyEvent keyEvent, boolean needWakeLock) {
1371 super(mHandler);
1372 mHandler.postDelayed(this, MEDIA_KEY_LISTENER_TIMEOUT);
1373 mKeyEvent = keyEvent;
1374 mNeedWakeLock = needWakeLock;
1375 }
1376
1377 @Override
1378 public void run() {
1379 Log.d(TAG, "The media key listener is timed-out for " + mKeyEvent);
1380 dispatchMediaKeyEvent();
1381 }
1382
1383 @Override
1384 protected void onReceiveResult(int resultCode, Bundle resultData) {
1385 if (resultCode == MediaSessionManager.RESULT_MEDIA_KEY_HANDLED) {
1386 mHandled = true;
1387 mHandler.removeCallbacks(this);
1388 return;
1389 }
1390 dispatchMediaKeyEvent();
1391 }
1392
1393 private void dispatchMediaKeyEvent() {
1394 if (mHandled) {
1395 return;
1396 }
1397 mHandled = true;
1398 mHandler.removeCallbacks(this);
1399 synchronized (mLock) {
1400 dispatchMediaKeyEventLocked(mKeyEvent, mNeedWakeLock, false);
1401 }
1402 }
1403 }
1404
RoboErik418c10c2014-05-19 09:25:25 -07001405 private KeyEventWakeLockReceiver mKeyEventReceiver = new KeyEventWakeLockReceiver(mHandler);
1406
RoboErikb214efb2014-07-24 13:20:30 -07001407 class KeyEventWakeLockReceiver extends ResultReceiver implements Runnable,
1408 PendingIntent.OnFinished {
RoboErik418c10c2014-05-19 09:25:25 -07001409 private final Handler mHandler;
1410 private int mRefCount = 0;
1411 private int mLastTimeoutId = 0;
1412
1413 public KeyEventWakeLockReceiver(Handler handler) {
1414 super(handler);
1415 mHandler = handler;
1416 }
1417
1418 public void onTimeout() {
1419 synchronized (mLock) {
1420 if (mRefCount == 0) {
1421 // We've already released it, so just return
1422 return;
1423 }
1424 mLastTimeoutId++;
1425 mRefCount = 0;
1426 releaseWakeLockLocked();
1427 }
1428 }
1429
1430 public void aquireWakeLockLocked() {
1431 if (mRefCount == 0) {
1432 mMediaEventWakeLock.acquire();
1433 }
1434 mRefCount++;
1435 mHandler.removeCallbacks(this);
1436 mHandler.postDelayed(this, WAKELOCK_TIMEOUT);
1437
1438 }
1439
1440 @Override
1441 public void run() {
1442 onTimeout();
1443 }
1444
RoboErik8a2cfc32014-05-16 11:19:38 -07001445 @Override
1446 protected void onReceiveResult(int resultCode, Bundle resultData) {
RoboErik418c10c2014-05-19 09:25:25 -07001447 if (resultCode < mLastTimeoutId) {
1448 // Ignore results from calls that were before the last
1449 // timeout, just in case.
1450 return;
1451 } else {
1452 synchronized (mLock) {
1453 if (mRefCount > 0) {
1454 mRefCount--;
1455 if (mRefCount == 0) {
1456 releaseWakeLockLocked();
1457 }
1458 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001459 }
1460 }
1461 }
RoboErik418c10c2014-05-19 09:25:25 -07001462
1463 private void releaseWakeLockLocked() {
1464 mMediaEventWakeLock.release();
1465 mHandler.removeCallbacks(this);
1466 }
RoboErikb214efb2014-07-24 13:20:30 -07001467
1468 @Override
1469 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
1470 String resultData, Bundle resultExtras) {
1471 onReceiveResult(resultCode, null);
1472 }
RoboErik8a2cfc32014-05-16 11:19:38 -07001473 };
1474
1475 BroadcastReceiver mKeyEventDone = new BroadcastReceiver() {
1476 @Override
1477 public void onReceive(Context context, Intent intent) {
1478 if (intent == null) {
1479 return;
1480 }
1481 Bundle extras = intent.getExtras();
1482 if (extras == null) {
1483 return;
1484 }
1485 synchronized (mLock) {
1486 if (extras.containsKey(EXTRA_WAKELOCK_ACQUIRED)
1487 && mMediaEventWakeLock.isHeld()) {
1488 mMediaEventWakeLock.release();
1489 }
1490 }
1491 }
1492 };
RoboErik01fe6612014-02-13 14:19:04 -08001493 }
1494
RoboErik2e7a9162014-06-04 16:53:45 -07001495 final class MessageHandler extends Handler {
1496 private static final int MSG_SESSIONS_CHANGED = 1;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001497 private static final int MSG_VOLUME_INITIAL_DOWN = 2;
RoboErik2e7a9162014-06-04 16:53:45 -07001498
1499 @Override
1500 public void handleMessage(Message msg) {
1501 switch (msg.what) {
1502 case MSG_SESSIONS_CHANGED:
1503 pushSessionsChanged(msg.arg1);
1504 break;
Jaewan Kimd61a87b2017-02-17 23:14:10 +09001505 case MSG_VOLUME_INITIAL_DOWN:
1506 synchronized (mLock) {
1507 UserRecord user = mUserRecords.get((int) msg.arg1);
1508 if (user != null && user.mInitialDownVolumeKeyEvent != null) {
1509 dispatchVolumeKeyLongPressLocked(user.mInitialDownVolumeKeyEvent);
1510 // Mark that the key is already handled.
1511 user.mInitialDownVolumeKeyEvent = null;
1512 }
1513 }
1514 break;
RoboErik2e7a9162014-06-04 16:53:45 -07001515 }
1516 }
1517
1518 public void post(int what, int arg1, int arg2) {
1519 obtainMessage(what, arg1, arg2).sendToTarget();
1520 }
1521 }
RoboErik01fe6612014-02-13 14:19:04 -08001522}