1 /* 2 * Copyright (C) 2016 Google Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not 5 * use this file except in compliance with the License. You may obtain a copy of 6 * 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, WITHOUT 12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the 13 * License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16 17 package com.googlecode.android_scripting.facade.media; 18 19 import android.content.Intent; 20 import android.media.session.MediaSession; 21 import android.os.Bundle; 22 import android.view.KeyEvent; 23 24 import com.googlecode.android_scripting.Log; 25 import com.googlecode.android_scripting.facade.EventFacade; 26 27 public class MediaButtonCallback extends MediaSession.Callback { 28 private final EventFacade mEventFacade; 29 public MediaButtonCallback(EventFacade eventFacade) { 30 this.mEventFacade = eventFacade; 31 } 32 private void handleKeyEvent(KeyEvent event) { 33 int keyCode = event.getKeyCode(); 34 Log.d("Received ACTION_DOWN with keycode " + keyCode); 35 Bundle msg = new Bundle(); 36 if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) { 37 msg.putString("ButtonPressed", "Play"); 38 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) { 39 msg.putString("ButtonPressed", "Pause"); 40 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) { 41 msg.putString("ButtonPressed", "PlayPause"); 42 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_STOP) { 43 msg.putString("ButtonPressed", "Stop"); 44 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_NEXT) { 45 msg.putString("ButtonPressed", "Next"); 46 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_PREVIOUS) { 47 msg.putString("ButtonPressed", "Previous"); 48 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_FAST_FORWARD) { 49 msg.putString("ButtonPressed", "Forward"); 50 } else if (keyCode == KeyEvent.KEYCODE_MEDIA_REWIND) { 51 msg.putString("ButtonPressed", "Rewind"); 52 } 53 Log.d("Sending MediaButton event with ButtonPressed value " 54 + msg.getString("ButtonPressed")); 55 this.mEventFacade.postEvent("MediaButton", msg); 56 } 57 58 @Override 59 public boolean onMediaButtonEvent(Intent mediaButtonIntent) { 60 String action = mediaButtonIntent.getAction(); 61 Log.d("Received intent with action " + action); 62 if (action.equals(Intent.ACTION_MEDIA_BUTTON)) { 63 KeyEvent event = (KeyEvent) mediaButtonIntent 64 .getParcelableExtra(Intent.EXTRA_KEY_EVENT); 65 int keyAction = event.getAction(); 66 Log.d("Received KeyEvent with action " + keyAction); 67 if (keyAction == KeyEvent.ACTION_DOWN) { 68 handleKeyEvent(event); 69 } else if (keyAction == KeyEvent.ACTION_UP) { 70 handleKeyEvent(event); 71 } 72 return true; 73 } 74 return super.onMediaButtonEvent(mediaButtonIntent); 75 } 76 }