Skip to content

Using USB MIDI Service

Kaoru Shoji edited this page Mar 20, 2015 · 1 revision

Currently, this feature has not been released yet. To test this feature, checkout the develop branch.

With using Service, several Activity, Fragment, or Service can interact with USB MIDI devices.
If the app want to connect with only one USB MIDI device, replace from MultipleMidiService to SingleMidiService.

Add the Service to the AndroidManifest.xml

    <service android:name="jp.kshoji.driver.midi.service.MultipleMidiService" android:exported="false" />

Add some code

Add MultipleMidiService and ServiceConnection field on the Activity or the Fragment.

    private MultipleMidiService midiService = null;

    private final ServiceConnection serviceConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            midiService = ((MultipleMidiService.LocalBinder)service).getService();
            midiService.setOnMidiDeviceAttachedListener(midiDeviceAttachedListener);
            midiService.setOnMidiDeviceDetachedListener(midiDeviceDetachedListener);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            midiService = null;
        }
    };

Initialize and finalize Service

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

        // start to use Service
        Intent intent = new Intent(this, MultipleMidiService.class);
        startService(intent);

        // attaches this context to Service
        bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT);

        ...
    }

   	@Override
	protected void onDestroy() {
		super.onDestroy();

        // detaches this context from Service
        unbindService(serviceConnection);

        // stop if all Service usage is finished.
        stopService(new Intent(this, MultipleMidiService.class));

        ...
    }

Use Service methods

Service has these methods to use USB MIDI.

  • getMidiOutputDevices
    • Obtains all the connected MidiOutputDevice.
  • getMidiInputDevices
    • Obtains all the connected MidiInputDevice.
  • setOnMidiDeviceAttachedListener
    • Set the listener to receive if the USB MIDI device become attached.
  • setOnMidiDeviceDetachedListener
    • Set the listener to receive if the USB MIDI device become detached.
  • resume
    • Stops to receive / send MIDI events.
  • suspend
    • Suspend from resume method.