1, 概述
media主要是和SessionManager进行交互,进行多媒体的播放、暂停等操作。
主要有三种命令,media dispatch KEY / media list-sessions / mediamonitor.本文主要以media dispatch KEY来论述。
2, media详细流程
Media的main方法如下,
public static void main(String[] args) {
(new Media()).run(args);
}
调用父类的run方法,然后调用子类的onRun方法,ronRun方法如下,
public void onRun() throws Exception {
mSessionService = ISessionManager.Stub.asInterface(ServiceManager.checkService(
Context.MEDIA_SESSION_SERVICE));
if (mSessionService == null) {
System.err.println(NO_SYSTEM_ERROR_CODE);
throw new AndroidException(
"Can't connect to media session service; is the system running?");
}
String op = nextArgRequired();
if (op.equals("dispatch")) {
runDispatch();
} else if (op.equals("list-sessions")) {
runListSessions();
} else if (op.equals("monitor")) {
runMonitor();
} else {
showError("Error: unknown command '" + op + "'");
return;
}
}
对dispatch的处理会调用 runDispatch方法
private void runDispatch() throws Exception {
String cmd = nextArgRequired();
int keycode;
if ("play".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_PLAY;
} else if ("pause".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_PAUSE;
} else if ("play-pause".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
} else if ("mute".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MUTE;
} else if ("headsethook".equals(cmd)) {
keycode = KeyEvent.KEYCODE_HEADSETHOOK;
} else if ("stop".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_STOP;
} else if ("next".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_NEXT;
} else if ("previous".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_PREVIOUS;
} else if ("rewind".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_REWIND;
} else if ("record".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_RECORD;
} else if ("fast-forward".equals(cmd)) {
keycode = KeyEvent.KEYCODE_MEDIA_FAST_FORWARD;
} else {
showError("Error: unknown dispatch code '" + cmd + "'");
return;
}
final long now = SystemClock.uptimeMillis();
sendMediaKey(new KeyEvent(now, now, KeyEvent.ACTION_DOWN, keycode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD));
sendMediaKey(new KeyEvent(now, now, KeyEvent.ACTION_UP, keycode, 0, 0,
KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD));
}
首先根据输入获取keycode,同样地2次调用sendMediaKey方法,分别是KeyEvent.ACTION_DOWN 和KeyEvent.ACTION_UP,该方法如下,
private void sendMediaKey(KeyEvent event) {
try {
mSessionService.dispatchMediaKeyEvent(event, false);
} catch (RemoteException e) {
}
}
最后调用SessionService的dispatchMediaKeyEvent方法来完成的。