如何为媒体播放器制作锁屏通知

SAV*_*VVY 5 android media-player lockscreen android-notifications android-mediaplayer

我试图在移动设备上获得锁定屏幕我能够让每件事情都像我的应用程序的通知和其他东西一样工作但是当我尝试显示锁定屏幕时它根本不适用于Android M.

private void initMediaSession() throws RemoteException {
    if (mediaSessionManager != null) return; //mediaSessionManager exists
    ComponentName mediaButtonReceiver = new ComponentName(getApplicationContext(), MediaButtonReceiver.class);

    mediaSession = new MediaSessionCompat(getApplicationContext(), "AudioPlayer", mediaButtonReceiver, null);
    //Get MediaSessions transport controls
    transportControls = mediaSession.getController().getTransportControls();
    //set MediaSession -> ready to receive media commands
    mediaSession.setActive(true);
    //indicate that the MediaSession handles transport control commands
    // through its MediaSessionCompat.Callback.
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
    mediaButtonIntent.setClass(this, MediaButtonReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, mediaButtonIntent, 0);
    mediaSession.setMediaButtonReceiver(pendingIntent);
    //Set mediaSession's MetaData
    updateMetaData();
    // passing the data


    // Attach Callback to receive MediaSession updates
    mediaSession.setCallback(new MediaSessionCompat.Callback() {
        // Implement callbacks
        @Override
        public void onPlay() {
            super.onPlay();
            messagesent();
            a = false;
            resumeMedia();
            buildNotification(PlaybackStatus.PLAYING);
        }

        @Override
        public void onPause() {
            super.onPause();
            messagesent();
            a = true;
            pauseMedia();
            buildNotification(PlaybackStatus.PAUSED);
        }

        @Override
        public void onSkipToNext() {
            super.onSkipToNext();

            skipToNext();
            updateMetaData();
            buildNotification(PlaybackStatus.PLAYING);
        }

        @Override
        public void onSkipToPrevious() {
            super.onSkipToPrevious();

            skipToPrevious();
            updateMetaData();
            buildNotification(PlaybackStatus.PLAYING);
        }

        @Override
        public void onStop() {
            super.onStop();
            removeNotification();
            //Stop the service
            pauseMedia();
            messagesent();
            stopSelf();
        }

        @Override
        public void onSeekTo(long position) {
            super.onSeekTo(position);
        }
    });
}

private void updateMetaData() {
    //replace with medias albumArt
    // Update the current metadata
    MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder();

    String artist;
    if (activeAudio.getArtist() != null) {
        artist = activeAudio.getArtist();
    } else {
        artist = "unknown";
    }
    String album;
    if (activeAudio.getAlbum() != null) {
        album = activeAudio.getAlbum();
    } else {
        album = "Album";
    }
    Bitmap albumArt;
    Uri myUri = Uri.parse(activeAudio.getAlbum_art());
    try {
        InputStream image_stream = getContentResolver().openInputStream(myUri);
        Bitmap bitmap = BitmapFactory.decodeStream(image_stream);
        if (bitmap != null) {
            albumArt = bitmap;
        } else {
            albumArt = BitmapFactory.decodeResource(getResources(),
                    R.drawable.music);
        }

    } catch (FileNotFoundException e) {
        e.printStackTrace();
        albumArt = BitmapFactory.decodeResource(getResources(),
                R.drawable.music);
    }
    metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_DISPLAY_ICON, albumArt);
    metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ALBUM_ART, albumArt);

    //lock screen icon for pre lollipop
    metadataBuilder.putBitmap(MediaMetadataCompat.METADATA_KEY_ART, albumArt);
    metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_TITLE, activeAudio.getTitle());
    metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_DISPLAY_SUBTITLE, activeAudio.getAlbum());
    metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ALBUM, album);
    metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_TRACK_NUMBER, 1);
    metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_NUM_TRACKS, 1);

    mediaSession.setMetadata(metadataBuilder.build());
}

private void buildNotification(PlaybackStatus playbackStatus) {

    /**
     * Notification actions -> playbackAction()
     *  0 -> Play
     *  1 -> Pause
     *  2 -> Next track
     *  3 -> Previous track
     */

    MediaControllerCompat controller = mediaSession.getController();
    MediaMetadataCompat mediaMetadata = controller.getMetadata();
    MediaDescriptionCompat description = mediaMetadata.getDescription();

    RemoteViews views = new RemoteViews(getPackageName(),
            R.layout.customnotification);


    if (playbackStatus == PlaybackStatus.PLAYING || Singleton.getInstance().getMedia() == 1) {
        views.setImageViewResource(R.id.imageButton2,
                R.drawable.ic_pause_circle_outline_white_48dp);

        messagesent();

        views.setOnClickPendingIntent(R.id.imageButton2, playbackAction(1));

    } else if (playbackStatus == PlaybackStatus.PAUSED || Singleton.getInstance().getMedia() == 2) {
        views.setImageViewResource(R.id.imageButton2,
                R.drawable.ic_play_circle_outline_white_48dp);
        messagesent();

        views.setOnClickPendingIntent(R.id.imageButton2, playbackAction(0));

    }

    views.setViewVisibility(R.id.imageView, View.VISIBLE);

    // Intent notificationIntent = new Intent(this, Main2Activity.class);

    // PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
    //         notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


    views.setOnClickPendingIntent(R.id.imageButton3, playbackAction(3));
    views.setOnClickPendingIntent(R.id.imageButton4, playbackAction(2));

    views.setImageViewResource(R.id.imageButton3,
            R.drawable.ic_skip_previous_circle_outline_white_36dp);
    views.setImageViewResource(R.id.imageButton4,
            R.drawable.ic_skip_next_circle_outline_white_36dp);
    views.setTextViewText(R.id.textView, description.getTitle());
    views.setTextViewText(R.id.textView2, description.getSubtitle());
    views.setImageViewBitmap(R.id.imageView, description.getIconBitmap());


   NotificationCompat.Builder sta = new NotificationCompat.Builder(this);
   //  sta.setContentIntent(pendingIntent);
    sta.setContent(views);
    sta.setSmallIcon(R.drawable.ic_audiotrack_white_24dp);
    sta.setStyle(new NotificationCompat.MediaStyle().setShowActionsInCompactView(0).setMediaSession(mediaSession.getSessionToken()));


    startForeground(Constants.NOTIFICATION_ID.FOREGROUND_SERVICE, sta.build());



}


public PendingIntent playbackAction(int actionNumber) {
    Intent playbackAction = new Intent(this, MediaService.class);
    switch (actionNumber) {
        case 0:
            // Play
            playbackAction.setAction(ACTION_PLAY);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 1:
            // Pause
            playbackAction.setAction(ACTION_PAUSE);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 2:
            // Next track
            playbackAction.setAction(ACTION_NEXT);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 3:
            // Previous track
            playbackAction.setAction(ACTION_PREVIOUS);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        case 4:
            playbackAction.setAction(Constants.ACTION.STOPFOREGROUND_ACTION);
            return PendingIntent.getService(this, actionNumber, playbackAction, 0);
        default:
            break;
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

我试图设置通知.setstyle,但它显示一些错误.我按照伊恩湖的视频,但仍然没有工作可以帮助我做错了什么

Zia*_*Zia 1

首先检查您的应用程序是否在 build.gradle 上使用 targetSdkVersion 22 运行。如果它有效,那么您有 Marshmallow 运行时权限相关问题。在 Manifest 上添加所需的权限,并在授予权限的情况下运行 initMediaSession()。详细信息Link1Link2

如果这对您没有帮助,请提供您的错误详细信息。