1 /* 2 * Copyright (C) 2015 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 */ 16 17 package com.example.android.common.midi; 18 19 import android.app.Activity; 20 import android.media.midi.MidiDevice; 21 import android.media.midi.MidiDeviceInfo; 22 import android.media.midi.MidiInputPort; 23 import android.media.midi.MidiManager; 24 import android.media.midi.MidiReceiver; 25 import android.os.Handler; 26 import android.os.Looper; 27 import android.util.Log; 28 29 import java.io.IOException; 30 31 /** 32 * Manages a Spinner for selecting a MidiInputPort. 33 */ 34 public class MidiInputPortSelector extends MidiPortSelector { 35 36 private MidiInputPort mInputPort; 37 private MidiDevice mOpenDevice; 38 39 /** 40 * @param midiManager 41 * @param activity 42 * @param spinnerId ID from the layout resource 43 */ MidiInputPortSelector(MidiManager midiManager, Activity activity, int spinnerId)44 public MidiInputPortSelector(MidiManager midiManager, Activity activity, 45 int spinnerId) { 46 super(midiManager, activity, spinnerId, MidiDeviceInfo.PortInfo.TYPE_INPUT); 47 } 48 49 @Override onPortSelected(final MidiPortWrapper wrapper)50 public void onPortSelected(final MidiPortWrapper wrapper) { 51 close(); 52 final MidiDeviceInfo info = wrapper.getDeviceInfo(); 53 if (info != null) { 54 mMidiManager.openDevice(info, new MidiManager.OnDeviceOpenedListener() { 55 @Override 56 public void onDeviceOpened(MidiDevice device) { 57 if (device == null) { 58 Log.e(MidiConstants.TAG, "could not open " + info); 59 } else { 60 mOpenDevice = device; 61 mInputPort = mOpenDevice.openInputPort( 62 wrapper.getPortIndex()); 63 if (mInputPort == null) { 64 Log.e(MidiConstants.TAG, "could not open input port on " + info); 65 } 66 } 67 } 68 }, null); 69 // Don't run the callback on the UI thread because openInputPort might take a while. 70 } 71 } 72 getReceiver()73 public MidiReceiver getReceiver() { 74 return mInputPort; 75 } 76 77 @Override onClose()78 public void onClose() { 79 try { 80 if (mInputPort != null) { 81 Log.i(MidiConstants.TAG, "MidiInputPortSelector.onClose() - close port"); 82 mInputPort.close(); 83 } 84 mInputPort = null; 85 if (mOpenDevice != null) { 86 mOpenDevice.close(); 87 } 88 mOpenDevice = null; 89 } catch (IOException e) { 90 Log.e(MidiConstants.TAG, "cleanup failed", e); 91 } 92 } 93 } 94