4

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

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

java.lang.NullPointerException:尝试在 android.os.Binder.queryLocalInterface(Binder.java:247) 的空对象引用上调用虚拟方法“boolean java.lang.String.equals(java.lang.Object)” .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) 在安卓。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(Native Method) 在 java.lang.reflect.Method.invoke (方法.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 视频,但我并不清楚如何做到这一点...任何示例源代码等都会很棒!

谢谢!

4

0 回答 0