我正在为 android 创建一个播放器应用程序,并希望MediaControllerCompat
从任何 UI 类访问。为此,我使用MediaBrowserCompat
类,我试图将它连接到我的MediaBrowserServiceCompat
并获得MediaControllerCompat
,MediaSessionCompat.Token
已经设置在我的Service
.
我试过MediaBrowserCompat.connect() 从不调用 onConnected 或任何 MediaBrowserCompat.ConnectionCallback 方法解决方案,但它没有帮助。
TortoiseActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tortoise);
mediaBrowser = new MediaBrowserCompat(
TortoiseActivity.this,
new ComponentName(TortoiseActivity.this, Service.class),
new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnected() {
try {
MediaSessionCompat.Token token = mediaBrowser.getSessionToken();
MediaControllerCompat controller = new MediaControllerCompat(TortoiseActivity.this, token);
MediaControllerCompat.setMediaController(TortoiseActivity.this, controller);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onConnectionFailed() {
Log.e("TAG", "onConnectionFailed");
}
@Override
public void onConnectionSuspended() {
Log.e("TAG", "onConnectionSuspended");
}
},
null);
mediaBrowser.connect();
}
服务.java
@Nullable
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
mediaSession = new MediaSessionCompat(this, Service.class.getSimpleName());
setSessionToken(mediaSession.getSessionToken());
mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setActive(true);
mediaSession.setCallback(callback);
}
SmallPlayerFragment.java
void initControls(Activity context) {
MediaControllerCompat mediaController = MediaControllerCompat.getMediaController(context);
this.transportControls = mediaController.getTransportControls();
}
结果,我得到了 NullPointer
java.lang.NullPointerException: Attempt to invoke virtual method 'android.support.v4.media.session.MediaControllerCompat$TransportControls android.support.v4.media.session.MediaControllerCompat.getTransportControls()' on a null object reference
at ru.krivocraft.kbmp.SmallPlayerFragment.initControls(SmallPlayerFragment.java:49)
at ru.krivocraft.kbmp.TortoiseActivity.getSmallPlayerFragment(TortoiseActivity.java:122)
at ru.krivocraft.kbmp.TortoiseActivity.showSmallPlayerFragment(TortoiseActivity.java:248)
at ru.krivocraft.kbmp.TortoiseActivity.access$200(TortoiseActivity.java:31)
at ru.krivocraft.kbmp.TortoiseActivity$4.onItemClick(TortoiseActivity.java:109)
当试图得到MediaControllerCompat.TrasportControls
. MediaControllerCompat
绝对是空的。我在 Callback 的 onConnected() 中设置了断点,但线程不会在其上挂起。所以,我可以得出结论,没有调用回调。