下面列出了怎么用android.media.session.MediaSession的API类实例代码及写法,或者点击链接到github查看源代码。
public void updateSession(MediaSessionRecord record) {
synchronized (mLock) {
FullUserRecord user = getFullUserRecordLocked(record.getUserId());
if (user == null) {
Log.w(TAG, "Unknown session updated. Ignoring.");
return;
}
if ((record.getFlags() & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
if (DEBUG_KEY_EVENT) {
Log.d(TAG, "Global priority session is updated, active=" + record.isActive());
}
user.pushAddressedPlayerChangedLocked();
} else {
if (!user.mPriorityStack.contains(record)) {
Log.w(TAG, "Unknown session updated. Ignoring.");
return;
}
user.mPriorityStack.onSessionStateChange(record);
}
mHandler.postSessionsChanged(record.getUserId());
}
}
private void updateActiveSessionListeners() {
synchronized (mLock) {
for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
SessionsListenerRecord listener = mSessionsListeners.get(i);
try {
enforceMediaPermissions(listener.mComponentName, listener.mPid, listener.mUid,
listener.mUserId);
} catch (SecurityException e) {
Log.i(TAG, "ActiveSessionsListener " + listener.mComponentName
+ " is no longer authorized. Disconnecting.");
mSessionsListeners.remove(i);
try {
listener.mListener
.onActiveSessionsChanged(new ArrayList<MediaSession.Token>());
} catch (Exception e1) {
// ignore
}
}
}
}
}
private void pushAddressedPlayerChangedLocked() {
if (mCallback == null) {
return;
}
try {
MediaSessionRecord mediaButtonSession = getMediaButtonSessionLocked();
if (mediaButtonSession != null) {
mCallback.onAddressedPlayerChangedToMediaSession(
new MediaSession.Token(mediaButtonSession.getControllerBinder()));
} else if (mCurrentFullUserRecord.mLastMediaButtonReceiver != null) {
mCallback.onAddressedPlayerChangedToMediaButtonReceiver(
mCurrentFullUserRecord.mLastMediaButtonReceiver
.getIntent().getComponent());
} else if (mCurrentFullUserRecord.mRestoredMediaButtonReceiver != null) {
mCallback.onAddressedPlayerChangedToMediaButtonReceiver(
mCurrentFullUserRecord.mRestoredMediaButtonReceiver);
}
} catch (RemoteException e) {
Log.w(TAG, "Failed to pushAddressedPlayerChangedLocked", e);
}
}
@Override
public void setFlags(int flags) {
if ((flags & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
int pid = getCallingPid();
int uid = getCallingUid();
mService.enforcePhoneStatePermission(pid, uid);
}
mFlags = flags;
if ((flags & MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY) != 0) {
final long token = Binder.clearCallingIdentity();
try {
mService.setGlobalPrioritySession(MediaSessionRecord.this);
} finally {
Binder.restoreCallingIdentity(token);
}
}
mHandler.post(MessageHandler.MSG_UPDATE_SESSION_STATE);
}
/**
* Notify the priority tracker that a session's playback state changed.
*
* @param record The record that changed.
* @param oldState Its old playback state.
* @param newState Its new playback state.
*/
public void onPlaystateChanged(MediaSessionRecord record, int oldState, int newState) {
if (shouldUpdatePriority(oldState, newState)) {
mSessions.remove(record);
mSessions.add(0, record);
clearCache(record.getUserId());
} else if (!MediaSession.isActiveState(newState)) {
// Just clear the volume cache when a state goes inactive
mCachedVolumeDefault = null;
}
// In most cases, playback state isn't needed for finding media button session,
// but we only use it as a hint if an app has multiple local media sessions.
// In that case, we pick the media session whose PlaybackState matches
// the audio playback configuration.
if (mMediaButtonSession != null && mMediaButtonSession.getUid() == record.getUid()) {
MediaSessionRecord newMediaButtonSession =
findMediaButtonSession(mMediaButtonSession.getUid());
if (newMediaButtonSession != mMediaButtonSession) {
updateMediaButtonSession(newMediaButtonSession);
}
}
}
@Override
public void onCreate() {
super.onCreate();
// Start a new MediaSession
mSession = new MediaSession(this, "MusicService");
mSession.setCallback(mCallback);
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
setSessionToken(mSession.getSessionToken());
final MediaNotificationManager mediaNotificationManager = new MediaNotificationManager(this);
mPlayback = new PlaybackManager(this, new PlaybackManager.Callback() {
@Override
public void onPlaybackStatusChanged(PlaybackState state) {
mSession.setPlaybackState(state);
mediaNotificationManager.update(mPlayback.getCurrentMedia(), state, getSessionToken());
}
});
}
@Override
public void onCreate() {
super.onCreate();
// Start a new MediaSession
mSession = new MediaSession(this, "MusicService");
mSession.setCallback(mCallback);
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
setSessionToken(mSession.getSessionToken());
final MediaNotificationManager mediaNotificationManager = new MediaNotificationManager(this);
mPlayback = new PlaybackManager(this, new PlaybackManager.Callback() {
@Override
public void onPlaybackStatusChanged(PlaybackState state) {
mSession.setPlaybackState(state);
mediaNotificationManager.update(mPlayback.getCurrentMedia(), state, getSessionToken());
}
});
}
@Override
public void onCreate() {
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mMediaSession = new MediaSession(this, TAG);
setUpCallBack();
mNotifications = new ArrayList<Botification>();
final IntentFilter filter = new IntentFilter();
filter.addAction(SERVICECMD);
// Attach the broadcast listener
mSharedPref = PreferenceManager.getDefaultSharedPreferences(this);
mHandler = new Handler(){
public void handleMessage(Message msg){
resetNotify(true);
}
};
}
private void pushSessionsChanged(int userId) {
synchronized (mLock) {
FullUserRecord user = getFullUserRecordLocked(userId);
if (user == null) {
Log.w(TAG, "pushSessionsChanged failed. No user with id=" + userId);
return;
}
List<MediaSessionRecord> records = getActiveSessionsLocked(userId);
int size = records.size();
ArrayList<MediaSession.Token> tokens = new ArrayList<MediaSession.Token>();
for (int i = 0; i < size; i++) {
tokens.add(new MediaSession.Token(records.get(i).getControllerBinder()));
}
pushRemoteVolumeUpdateLocked(userId);
for (int i = mSessionsListeners.size() - 1; i >= 0; i--) {
SessionsListenerRecord record = mSessionsListeners.get(i);
if (record.mUserId == UserHandle.USER_ALL || record.mUserId == userId) {
try {
record.mListener.onActiveSessionsChanged(tokens);
} catch (RemoteException e) {
Log.w(TAG, "Dead ActiveSessionsListener in pushSessionsChanged, removing",
e);
mSessionsListeners.remove(i);
}
}
}
}
}
@Override
public void onCreate() {
super.onCreate();
ApplicationLoader.postInitApplication();
lastSelectedDialog = MessagesController.getNotificationsSettings(currentAccount).getInt("auto_lastSelectedDialog", 0);
mediaSession = new MediaSession(this, "MusicService");
setSessionToken(mediaSession.getSessionToken());
mediaSession.setCallback(new MediaSessionCallback());
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
Context context = getApplicationContext();
Intent intent = new Intent(context, LaunchActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mediaSession.setSessionActivity(pi);
Bundle extras = new Bundle();
extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
mediaSession.setExtras(extras);
updatePlaybackState(null);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStarted);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
String args[] = mediaId.split("_");
if (args.length != 2) {
return;
}
try {
int did = Integer.parseInt(args[0]);
int id = Integer.parseInt(args[1]);
ArrayList<MessageObject> arrayList = musicObjects.get(did);
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
if (arrayList == null || id < 0 || id >= arrayList.size()) {
return;
}
lastSelectedDialog = did;
MessagesController.getNotificationsSettings(currentAccount).edit().putInt("auto_lastSelectedDialog", did).commit();
MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), false);
mediaSession.setQueue(arrayList1);
if (did > 0) {
TLRPC.User user = users.get(did);
if (user != null) {
mediaSession.setQueueTitle(ContactsController.formatName(user.first_name, user.last_name));
} else {
mediaSession.setQueueTitle("DELETED USER");
}
} else {
TLRPC.Chat chat = chats.get(-did);
if (chat != null) {
mediaSession.setQueueTitle(chat.title);
} else {
mediaSession.setQueueTitle("DELETED CHAT");
}
}
} catch (Exception e) {
FileLog.e(e);
}
handlePlayRequest();
}
@Override
public void onCreate() {
super.onCreate();
ApplicationLoader.postInitApplication();
lastSelectedDialog = MessagesController.getNotificationsSettings(currentAccount).getInt("auto_lastSelectedDialog", 0);
mediaSession = new MediaSession(this, "MusicService");
setSessionToken(mediaSession.getSessionToken());
mediaSession.setCallback(new MediaSessionCallback());
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
Context context = getApplicationContext();
Intent intent = new Intent(context, LaunchActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mediaSession.setSessionActivity(pi);
Bundle extras = new Bundle();
extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
mediaSession.setExtras(extras);
updatePlaybackState(null);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStarted);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
String args[] = mediaId.split("_");
if (args.length != 2) {
return;
}
try {
int did = Integer.parseInt(args[0]);
int id = Integer.parseInt(args[1]);
ArrayList<MessageObject> arrayList = musicObjects.get(did);
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
if (arrayList == null || id < 0 || id >= arrayList.size()) {
return;
}
lastSelectedDialog = did;
MessagesController.getNotificationsSettings(currentAccount).edit().putInt("auto_lastSelectedDialog", did).commit();
MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), false);
mediaSession.setQueue(arrayList1);
if (did > 0) {
TLRPC.User user = users.get(did);
if (user != null) {
mediaSession.setQueueTitle(ContactsController.formatName(user.first_name, user.last_name));
} else {
mediaSession.setQueueTitle("DELETED USER");
}
} else {
TLRPC.Chat chat = chats.get(-did);
if (chat != null) {
mediaSession.setQueueTitle(chat.title);
} else {
mediaSession.setQueueTitle("DELETED CHAT");
}
}
} catch (Exception e) {
FileLog.e(e);
}
handlePlayRequest();
}
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
mContext = this;
mSession = new MediaSession(this, "WearBrowserService");
setSessionToken(mSession.getSessionToken());
mSession.setCallback(new MediaSessionCallback());
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
}
@Override
public void onCreate() {
super.onCreate();
mSession = new MediaSession(this, "ExoPlayerAudio");
setSessionToken(mSession.getSessionToken());
mSession.setCallback(new MediaSessionCallback());
mSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
}
private void setUpMediaSession() {
mediaSession = new MediaSession(this, TAG);
mediaSession.setActive(true);
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
mediaSession.setPlaybackState(
new PlaybackState.Builder()
.setState(PlaybackState.STATE_PLAYING, 0L, 0F)
.setActions(PlaybackState.ACTION_PAUSE |
PlaybackState.ACTION_PLAY |
PlaybackState.ACTION_REWIND |
PlaybackState.ACTION_FAST_FORWARD)
.build());
mediaSession.setMetadata(new MediaMetadata.Builder().build());
}
private void unregister() {
for (Map.Entry<MediaSession.Token, Pair<MediaController, MediaController.Callback>> entry : mControllers.entrySet()) {
Pair<MediaController, MediaController.Callback> pair = entry.getValue();
pair.first.unregisterCallback(pair.second);
}
synchronized (mControllers) {
mControllers.clear();
}
}
@Override
public ChromeNotificationBuilder setMediaStyle(MediaSessionCompat session, int[] actions,
PendingIntent intent, boolean showCancelButton) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Notification.MediaStyle style = new Notification.MediaStyle();
style.setMediaSession(((MediaSession) session.getMediaSession()).getSessionToken());
style.setShowActionsInCompactView(actions);
mBuilder.setStyle(style);
}
return this;
}
private void unregister() {
for (Map.Entry<MediaSession.Token, Pair<MediaController, MediaController.Callback>> entry : mControllers.entrySet()) {
Pair<MediaController, MediaController.Callback> pair = entry.getValue();
pair.first.unregisterCallback(pair.second);
}
synchronized (mControllers) {
mControllers.clear();
}
}
@Override
public void onCreate() {
super.onCreate();
ApplicationLoader.postInitApplication();
lastSelectedDialog = MessagesController.getNotificationsSettings(currentAccount).getInt("auto_lastSelectedDialog", 0);
mediaSession = new MediaSession(this, "MusicService");
setSessionToken(mediaSession.getSessionToken());
mediaSession.setCallback(new MediaSessionCallback());
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
Context context = getApplicationContext();
Intent intent = new Intent(context, LaunchActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mediaSession.setSessionActivity(pi);
Bundle extras = new Bundle();
extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
mediaSession.setExtras(extras);
updatePlaybackState(null);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
String args[] = mediaId.split("_");
if (args.length != 2) {
return;
}
try {
int did = Integer.parseInt(args[0]);
int id = Integer.parseInt(args[1]);
ArrayList<MessageObject> arrayList = musicObjects.get(did);
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
if (arrayList == null || id < 0 || id >= arrayList.size()) {
return;
}
lastSelectedDialog = did;
MessagesController.getNotificationsSettings(currentAccount).edit().putInt("auto_lastSelectedDialog", did).commit();
MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), false);
mediaSession.setQueue(arrayList1);
if (did > 0) {
TLRPC.User user = users.get(did);
if (user != null) {
mediaSession.setQueueTitle(ContactsController.formatName(user.first_name, user.last_name));
} else {
mediaSession.setQueueTitle("DELETED USER");
}
} else {
TLRPC.Chat chat = chats.get(-did);
if (chat != null) {
mediaSession.setQueueTitle(chat.title);
} else {
mediaSession.setQueueTitle("DELETED CHAT");
}
}
} catch (Exception e) {
FileLog.e(e);
}
handlePlayRequest();
}
private void initMediaSession() {
mMediaSession = new MediaSession( this, "Android Auto Audio Demo" );
mMediaSession.setActive( true );
mMediaSession.setCallback( mMediaSessionCallback );
mMediaSessionToken = mMediaSession.getSessionToken();
setSessionToken( mMediaSessionToken );
}
private void setUpCallBack() {
mMediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS |
MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
mMediaSession.setCallback(new MediaSession.Callback() {
@Override
public void onPlay() {
super.onPlay();
removeNotification();
}
@Override
public void onPause() {
super.onPause();
removeNotification();
}
@Override
public void onSkipToNext() {
super.onSkipToNext();
showNotify(1);
}
@Override
public void onSkipToPrevious() {
super.onSkipToPrevious();
}
@Override
public void onStop() {
super.onStop();
resetNotify(true);
showNotify(-1);
}
});
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public void setMediaSessionCompat(MediaSession mediaSession) {
if (mediaSession == null) {
return;
}
//mNotificationBuilder.setStyle(new Notification.MediaStyle()
// .setMediaSession(mediaSession.getSessionToken()));
}
@Override
public void onCreate() {
super.onCreate();
ApplicationLoader.postInitApplication();
lastSelectedDialog = MessagesController.getNotificationsSettings(currentAccount).getInt("auto_lastSelectedDialog", 0);
mediaSession = new MediaSession(this, "MusicService");
setSessionToken(mediaSession.getSessionToken());
mediaSession.setCallback(new MediaSessionCallback());
mediaSession.setFlags(MediaSession.FLAG_HANDLES_MEDIA_BUTTONS | MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
Context context = getApplicationContext();
Intent intent = new Intent(context, LaunchActivity.class);
PendingIntent pi = PendingIntent.getActivity(context, 99, intent, PendingIntent.FLAG_UPDATE_CURRENT);
mediaSession.setSessionActivity(pi);
Bundle extras = new Bundle();
extras.putBoolean(SLOT_RESERVATION_QUEUE, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_PREV, true);
extras.putBoolean(SLOT_RESERVATION_SKIP_TO_NEXT, true);
mediaSession.setExtras(extras);
updatePlaybackState(null);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidStart);
NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.messagePlayingDidReset);
}
@Override
public void onPlayFromMediaId(String mediaId, Bundle extras) {
String args[] = mediaId.split("_");
if (args.length != 2) {
return;
}
try {
int did = Integer.parseInt(args[0]);
int id = Integer.parseInt(args[1]);
ArrayList<MessageObject> arrayList = musicObjects.get(did);
ArrayList<MediaSession.QueueItem> arrayList1 = musicQueues.get(did);
if (arrayList == null || id < 0 || id >= arrayList.size()) {
return;
}
lastSelectedDialog = did;
MessagesController.getNotificationsSettings(currentAccount).edit().putInt("auto_lastSelectedDialog", did).commit();
MediaController.getInstance().setPlaylist(arrayList, arrayList.get(id), false);
mediaSession.setQueue(arrayList1);
if (did > 0) {
TLRPC.User user = users.get(did);
if (user != null) {
mediaSession.setQueueTitle(ContactsController.formatName(user.first_name, user.last_name));
} else {
mediaSession.setQueueTitle("DELETED USER");
}
} else {
TLRPC.Chat chat = chats.get(-did);
if (chat != null) {
mediaSession.setQueueTitle(chat.title);
} else {
mediaSession.setQueueTitle("DELETED CHAT");
}
}
} catch (Exception e) {
FileLog.e(e);
}
handlePlayRequest();
}
/**
* Send a volume adjustment to the session owner. Direction must be one of
* {@link AudioManager#ADJUST_LOWER}, {@link AudioManager#ADJUST_RAISE},
* {@link AudioManager#ADJUST_SAME}.
*
* @param packageName The package that made the original volume request.
* @param pid The pid that made the original volume request.
* @param uid The uid that made the original volume request.
* @param caller caller binder. can be {@code null} if it's from the volume key.
* @param asSystemService {@code true} if the event sent to the session as if it was come from
* the system service instead of the app process. This helps sessions to distinguish
* between the key injection by the app and key events from the hardware devices.
* Should be used only when the volume key events aren't handled by foreground
* activity. {@code false} otherwise to tell session about the real caller.
* @param direction The direction to adjust volume in.
* @param flags Any of the flags from {@link AudioManager}.
* @param useSuggested True to use adjustSuggestedStreamVolume instead of
*/
public void adjustVolume(String packageName, int pid, int uid,
ISessionControllerCallback caller, boolean asSystemService, int direction, int flags,
boolean useSuggested) {
int previousFlagPlaySound = flags & AudioManager.FLAG_PLAY_SOUND;
if (isPlaybackActive() || hasFlag(MediaSession.FLAG_EXCLUSIVE_GLOBAL_PRIORITY)) {
flags &= ~AudioManager.FLAG_PLAY_SOUND;
}
if (mVolumeType == PlaybackInfo.PLAYBACK_TYPE_LOCAL) {
// Adjust the volume with a handler not to be blocked by other system service.
int stream = AudioAttributes.toLegacyStreamType(mAudioAttrs);
postAdjustLocalVolume(stream, direction, flags, packageName, uid, useSuggested,
previousFlagPlaySound);
} else {
if (mVolumeControlType == VolumeProvider.VOLUME_CONTROL_FIXED) {
// Nothing to do, the volume cannot be changed
return;
}
if (direction == AudioManager.ADJUST_TOGGLE_MUTE
|| direction == AudioManager.ADJUST_MUTE
|| direction == AudioManager.ADJUST_UNMUTE) {
Log.w(TAG, "Muting remote playback is not supported");
return;
}
mSessionCb.adjustVolume(packageName, pid, uid, caller, asSystemService, direction);
int volumeBefore = (mOptimisticVolume < 0 ? mCurrentVolume : mOptimisticVolume);
mOptimisticVolume = volumeBefore + direction;
mOptimisticVolume = Math.max(0, Math.min(mOptimisticVolume, mMaxVolume));
mHandler.removeCallbacks(mClearOptimisticVolumeRunnable);
mHandler.postDelayed(mClearOptimisticVolumeRunnable, OPTIMISTIC_VOLUME_TIMEOUT);
if (volumeBefore != mOptimisticVolume) {
pushVolumeUpdate();
}
mService.notifyRemoteVolumeChanged(flags, this);
if (DEBUG) {
Log.d(TAG, "Adjusted optimistic volume to " + mOptimisticVolume + " max is "
+ mMaxVolume);
}
}
}
public boolean isTransportControlEnabled() {
return hasFlag(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);
}
@Override
public void onCreate() {
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
for (int a = 0; a < UserConfig.MAX_ACCOUNT_COUNT; a++) {
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingDidSeek);
NotificationCenter.getInstance(a).addObserver(this, NotificationCenter.messagePlayingPlayStateChanged);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
mediaSession = new MediaSession(this, "telegramAudioPlayer");
playbackState = new PlaybackState.Builder();
albumArtPlaceholder = Bitmap.createBitmap(AndroidUtilities.dp(102), AndroidUtilities.dp(102), Bitmap.Config.ARGB_8888);
Drawable placeholder = getResources().getDrawable(R.drawable.nocover_big);
placeholder.setBounds(0, 0, albumArtPlaceholder.getWidth(), albumArtPlaceholder.getHeight());
placeholder.draw(new Canvas(albumArtPlaceholder));
mediaSession.setCallback(new MediaSession.Callback() {
@Override
public void onPlay() {
MediaController.getInstance().playMessage(MediaController.getInstance().getPlayingMessageObject());
}
@Override
public void onPause() {
MediaController.getInstance().pauseMessage(MediaController.getInstance().getPlayingMessageObject());
}
@Override
public void onSkipToNext() {
MediaController.getInstance().playNextMessage();
}
@Override
public void onSkipToPrevious() {
MediaController.getInstance().playPreviousMessage();
}
@Override
public void onStop() {
//stopSelf();
}
});
mediaSession.setActive(true);
}
super.onCreate();
}
private void setupMediaSession() {
ComponentName mediaButtonReceiverComponentName = new ComponentName(getApplicationContext(), MediaButtonIntentReceiver.class);
Intent mediaButtonIntent = new Intent(Intent.ACTION_MEDIA_BUTTON);
mediaButtonIntent.setComponent(mediaButtonReceiverComponentName);
PendingIntent mediaButtonReceiverPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mediaButtonIntent, 0);
mediaSession = new MediaSessionCompat(this, getResources().getString(R.string.main_activity_name), mediaButtonReceiverComponentName, mediaButtonReceiverPendingIntent);
mediaSession.setCallback(new MediaSessionCompat.Callback() {
@Override
public void onPlay() {
play();
}
@Override
public void onPause() {
pause();
}
@Override
public void onSkipToNext() {
playNextSong(true);
}
@Override
public void onSkipToPrevious() {
back(true);
}
@Override
public void onStop() {
quit();
}
@Override
public void onSeekTo(long pos) {
seek((int) pos);
}
@Override
public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
return MediaButtonIntentReceiver.handleIntent(MusicService.this, mediaButtonEvent);
}
});
mediaSession.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS
| MediaSession.FLAG_HANDLES_MEDIA_BUTTONS);
mediaSession.setMediaButtonReceiver(mediaButtonReceiverPendingIntent);
}