1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16package android.support.v4.media.session; 17 18import android.app.PendingIntent; 19import android.content.Context; 20import android.media.AudioManager; 21import android.media.RemoteControlClient; 22import android.os.SystemClock; 23 24public class MediaSessionCompatApi18 { 25 26 public static Object createPlaybackPositionUpdateListener( 27 MediaSessionCompatApi14.Callback callback) { 28 return new OnPlaybackPositionUpdateListener<MediaSessionCompatApi14.Callback>(callback); 29 } 30 31 public static void registerMediaButtonEventReceiver(Context context, PendingIntent pi) { 32 AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 33 am.registerMediaButtonEventReceiver(pi); 34 } 35 36 public static void unregisterMediaButtonEventReceiver(Context context, PendingIntent pi) { 37 AudioManager am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); 38 am.unregisterMediaButtonEventReceiver(pi); 39 } 40 41 public static void setState(Object rccObj, int state, long position, float speed, 42 long updateTime) { 43 long currTime = SystemClock.elapsedRealtime(); 44 if (state == MediaSessionCompatApi14.STATE_PLAYING && position > 0) { 45 long diff = 0; 46 if (updateTime > 0) { 47 diff = currTime - updateTime; 48 if (speed > 0 && speed != 1f) { 49 diff *= speed; 50 } 51 } 52 position += diff; 53 } 54 state = MediaSessionCompatApi14.getRccStateFromState(state); 55 ((RemoteControlClient) rccObj).setPlaybackState(state, position, speed); 56 } 57 58 public static void setOnPlaybackPositionUpdateListener(Object rccObj, 59 Object onPositionUpdateObj) { 60 ((RemoteControlClient) rccObj).setPlaybackPositionUpdateListener( 61 (RemoteControlClient.OnPlaybackPositionUpdateListener) onPositionUpdateObj); 62 } 63 64 static class OnPlaybackPositionUpdateListener<T extends MediaSessionCompatApi14.Callback> 65 implements RemoteControlClient.OnPlaybackPositionUpdateListener { 66 protected final T mCallback; 67 68 public OnPlaybackPositionUpdateListener(T callback) { 69 mCallback = callback; 70 } 71 72 @Override 73 public void onPlaybackPositionUpdate(long newPositionMs) { 74 mCallback.onSeekTo(newPositionMs); 75 } 76 } 77}