Fix playback state callback crash
Fixes: 132901314
Test: Manual
Change-Id: If02629274fc9abc1a54f0d6955da9a2072b46353
(cherry picked from commit 2f22e768ed8f160229aabab3891fd54fa93b89e3)
diff --git a/service/src/com/android/car/CarMediaService.java b/service/src/com/android/car/CarMediaService.java
index a4e0d6e..10d5d91 100644
--- a/service/src/com/android/car/CarMediaService.java
+++ b/service/src/com/android/car/CarMediaService.java
@@ -34,6 +34,8 @@
import android.media.session.MediaSessionManager;
import android.media.session.MediaSessionManager.OnActiveSessionsChangedListener;
import android.media.session.PlaybackState;
+import android.os.Handler;
+import android.os.HandlerThread;
import android.os.RemoteCallbackList;
import android.os.RemoteException;
import android.service.media.MediaBrowserService;
@@ -85,6 +87,10 @@
private RemoteCallbackList<ICarMediaSourceListener> mMediaSourceListeners =
new RemoteCallbackList();
+ // Handler to receive PlaybackState callbacks from the active media controller.
+ private Handler mHandler;
+ private HandlerThread mHandlerThread;
+
/** The package name of the last media source that was removed while being primary. */
private String mRemovedMediaSourcePackage;
@@ -128,6 +134,10 @@
mMediaSessionManager = mContext.getSystemService(MediaSessionManager.class);
mMediaSessionUpdater = new MediaSessionUpdater();
+ mHandlerThread = new HandlerThread(CarLog.TAG_MEDIA);
+ mHandlerThread.start();
+ mHandler = new Handler(mHandlerThread.getLooper());
+
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
@@ -463,7 +473,11 @@
if (mPrimaryMediaPackage.equals(controller.getPackageName())) {
mActiveUserMediaController = controller;
savePlaybackState(mActiveUserMediaController.getPlaybackState());
- mActiveUserMediaController.registerCallback(mMediaControllerCallback);
+ // Specify Handler to receive callbacks on, to avoid defaulting to the calling
+ // thread; this method can be called from the MediaSessionManager callback.
+ // Using the version of this method without passing a handler causes a
+ // RuntimeException for failing to create a Handler.
+ mActiveUserMediaController.registerCallback(mMediaControllerCallback, mHandler);
return;
}
}