Проблемы с настройкой MediaBrowserService и MediaSession
Я хочу обновить мое приложение до последних стандартов Android, поэтому я хочу внедрить MediaSession и еще MediaBrowserCompat для управления моим воспроизведением.
На самом деле я получаю эту ошибку:
java.lang.NullPointerException: попытка вызвать виртуальный метод 'boolean java.lang.String.equals(java.lang.Object)' для нулевой ссылки на объект на android.os.Binder.queryLocalInterface(Binder.java:247) на android.service.media.IMediaBrowserService$Stub.asInterface(IMediaBrowserService.java:31) в android.media.browse.MediaBrowser$MediaServiceConnection.onServiceConnected(MediaBrowser.java:709) в android.app.Loadednek:1209) в android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1226) в android.os.Handler.handleCallback(Handler.java:739) в android.os.Handler.dispatchMessage(Handler.java:95) на android.os.Looper.loop(Looper.java:135) на android.app.ActivityThread.main(ActivityThread.java:5294) на java.lang.reflect.Method.invoke(собственный метод) на java.lang.reflect.Method.invoke(Method.java:372) на com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) на com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
Вызывается этим кодом:
mMediaBrowser = new MediaBrowserCompat(this, new ComponentName(this, MusicService.class), new MediaBrowserCompat.ConnectionCallback() {
@Override
public void onConnectionSuspended() {
super.onConnectionSuspended();
}
@Override
public void onConnectionFailed() {
super.onConnectionFailed();
}
@Override
public void onConnected() {
super.onConnected();
if (MusicPlayer.isPreparing() || MusicPlayer.isPlaying()) {
Start_Timer();
}
}
}, null);
mMediaBrowser.connect();
А вот часть моего MusicService:
public class MusicService extends MediaBrowserServiceCompat
implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnErrorListener {
@Override
public void onCreate() {
super.onCreate();
InitMediaPlayer();
mMediaSession = new MediaSessionCompat(getApplicationContext(), MusicService.class.getSimpleName());
mAudioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
mPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
iCurrentSongIndex = 0;
iSeekTo = -1;
bPlayingFromQueue = false;
bStarted = bPreparing = bRestartAfterLoss = bControlReceiverRegistered = false;
mPlayMode = PlayMode.PASS;
mSongQueue = new ArrayList<>();
nManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
int iRequestResult = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
if (iRequestResult != AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Toast.makeText(getApplicationContext(), "Couldn't gain the Permission to play music!", Toast.LENGTH_LONG).show();
stopForeground(true);
stopSelf();
System.exit(0);
return;
}
mControlReceiver = new MediaControlReceiver();
IntentFilter infNotification = new IntentFilter();
infNotification.addAction(MediaControlReceiver.NOTIFY_PLAYPAUSE);
infNotification.addAction(MediaControlReceiver.NOTIFY_PREVIOUS);
infNotification.addAction(MediaControlReceiver.NOTIFY_NEXT);
infNotification.addAction(MediaControlReceiver.NOTIFY_CANCEL);
infNotification.addAction(AudioManager.ACTION_AUDIO_BECOMING_NOISY);
if (!bControlReceiverRegistered) {
registerReceiver(mControlReceiver, infNotification);
bControlReceiverRegistered = true;
}
mRemoteControlComponent = new ComponentName(this, RemoteControlReceiver.class);
mAudioManager.registerMediaButtonEventReceiver(mRemoteControlComponent);
getTheme().applyStyle(RuntimeInfo.getThemeID(), true);
}
private Notification Build_Notification() {
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
nBuilder.setShowWhen(false);
TypedValue typedValue = new TypedValue();
getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);
int iPrimaryColor = typedValue.data;
nBuilder.setColor(iPrimaryColor);
Intent notIntent = new Intent(getApplicationContext(), MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent notOpenOnClick = PendingIntent.getActivity(getApplicationContext(), 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mMediaSession.setActive(true);
ArtworkProvider artworkProvider = new ArtworkProvider(this);
MediaMetadataCompat.Builder mMetaDataBuilder = new MediaMetadataCompat.Builder();
Bitmap bCover = artworkProvider.getAlbumArtwork(getCurrentSong().getAlbumID(), 150, 150);
mMetaDataBuilder
.putString(MediaMetadataCompat.METADATA_KEY_TITLE, getCurrentSong().getTitle())
.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, getCurrentSong().getAlbum())
.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, getCurrentSong().getArtist());
String ArtworkOnLockscreenKey = getString(R.string.keyArtworkOnLockscreen);
boolean bArtworkOnLockscreen = mPreferences.getBoolean(ArtworkOnLockscreenKey, true);
if (bArtworkOnLockscreen) {
mMetaDataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, bCover);
}
MediaMetadataCompat mMetadata = mMetaDataBuilder.build();
mMediaSession.setMetadata(mMetadata);
mMediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
nBuilder.setSmallIcon(R.drawable.not_icon)
.setContentTitle(mMetadata.getString(MediaMetadataCompat.METADATA_KEY_TITLE))
.setContentText(mMetadata.getString(MediaMetadataCompat.METADATA_KEY_ALBUM) + Constants.Char.SEPERATOR_DOT + mMetadata.getString(MediaMetadataCompat.METADATA_KEY_ARTIST))
.setLargeIcon(bCover)
.setContentIntent(notOpenOnClick);
if (MainActivity.isActive()) {
nBuilder.setOngoing(true);
}
PendingIntent pPrevious = MediaStyleHelper.getActionIntent(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_PREVIOUS);
PendingIntent pPlayPause = MediaStyleHelper.getActionIntent(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE);
PendingIntent pNext = MediaStyleHelper.getActionIntent(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_NEXT);
PendingIntent pCancel = MediaStyleHelper.getActionIntent(getApplicationContext(), KeyEvent.KEYCODE_MEDIA_STOP);
nBuilder.addAction(R.drawable.ic_previous_48dp, MediaControlReceiver.NOTIFY_PREVIOUS, pPrevious);
if (isPreparing() || isPlaying()) {
nBuilder.addAction(R.drawable.ic_pause_48dp, MediaControlReceiver.NOTIFY_PLAYPAUSE, pPlayPause);
}
else {
nBuilder.addAction(R.drawable.ic_play_48dp, MediaControlReceiver.NOTIFY_PLAYPAUSE, pPlayPause);
}
nBuilder.addAction(R.drawable.ic_next_48dp, MediaControlReceiver.NOTIFY_NEXT, pNext);
nBuilder.setStyle(new NotificationCompat.MediaStyle()
.setMediaSession(mMediaSession.getSessionToken())
.setShowActionsInCompactView(1, 2)
.setShowCancelButton(true)
.setCancelButtonIntent(pCancel));
nBuilder.setDeleteIntent(pCancel);
mNotification = nBuilder.build();
return mNotification;
}
}
Надеюсь, вы мне поможете... Я смотрел видео на Google Developer на YouTube, но мне не совсем понятно, как это сделать... Любой пример исходного кода и т. Д. Был бы великолепен!
Спасибо!