您可以在以下位置找到我的源代码:https://github.com/Ali-Rezaei/ExoPlayerSample
我的服务中有一个ExoPlayer:
public class MainService extends Service implements ExoPlayer.EventListener {
private SimpleExoPlayer mExoPlayer;
private static MediaSessionCompat mMediaSession;
@Override
public void onCreate() {
super.onCreate();
// Initialize the Media Session.
initializeMediaSession();
// Initialize the player.
initializePlayer();
}
@Override
public IBinder onBind(Intent intent) {
return new MainServiceBinder();
}
@Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Intent broadcastIntent = new Intent(this, RestartService.class);
broadcastIntent.setAction("restartService");
sendBroadcast(broadcastIntent);
}
/**
* Release ExoPlayer.
*/
private void releasePlayer() {
mNotificationManager.cancelAll();
mExoPlayer.removeListener(this);
mExoPlayer.stop();
mExoPlayer.release();
mExoPlayer = null;
}
/**
* Release the player when the service is destroyed.
*/
@Override
public void onDestroy() {
super.onDestroy();
releasePlayer();
mMediaSession.setActive(false);
}
/**
* Broadcast Receiver registered to receive the MEDIA_BUTTON intent coming from clients.
*/
public static class MediaReceiver extends BroadcastReceiver {
public MediaReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
MediaButtonReceiver.handleIntent(mMediaSession, intent);
}
}
public static class RestartService extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MainService.class));
}
}
}
我正在显示如下通知:
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "Id");
Notification notificationCompat = builder.build();
if (state.getState() == PlaybackStateCompat.STATE_PAUSED) {
stopForeground(true);
mNotificationManager.cancel(NOTIFICATION_ID);
mNotificationManager.notify(NOTIFICATION_ID, notificationCompat);
} else {
startForeground(NOTIFICATION_ID, notificationCompat);
}
[当我关闭应用程序时(使用设备后退或主页按钮),或者从最近的应用程序中关闭您的应用程序(手动杀死该应用程序,然后单击暂停/播放通知->通知将关闭并再次显示。我的期望:我不希望像SoundCloud应用程序那样解雇并再次显示。我想念什么?
StopForground
时,我不应该删除通知。因此,我的逻辑应如下:
Notification notificationCompat = builder.build();
if (state.getState() == PlaybackStateCompat.STATE_PAUSED) {
stopForeground(false);
mNotificationManager.notify(NOTIFICATION_ID, notificationCompat);
} else {
startForeground(NOTIFICATION_ID, notificationCompat);
}