设置MediaBrowserService和MediaSession的麻烦

时间:2016-08-12 19:19:02

标签: java android playback android-mediasession

我想将我的应用更新到最新的android标准,所以我想实现MediaSession和MediaBrowserCompat来控制我的播放。

实际上我收到了这个错误:

  

java.lang.NullPointerException:尝试调用虚方法   ' boolean java.lang.String.equals(java.lang.Object)'在null对象上   参考                                                                        在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.LoadedApk $ ServiceDispatcher.doConnected(LoadedApk.java: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)                                                                        at java.lang.reflect.Method.invoke(Native Method)                                                                        在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;
    }
}

我希望你能帮助我...... 我在youtube上观看了Google Developer视频,但对我来说,如何做到这一点并不是很清楚...... 任何示例源代码等都会很棒!

谢谢!

0 个答案:

没有答案