Skip to content

Using BLE MIDI Service

Kaoru Shoji edited this page Mar 31, 2015 · 2 revisions

With using BleMidiCentralService, several Activity, Fragment, or Service can interact with BLE MIDI devices.
With using BleMidiPeripheralService, several Activity, Fragment, or Service can pretend as BLE MIDI devices.

Add the Service to the AndroidManifest.xml

With BleMidiCentralService:

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

With BleMidiPeripheralService:

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

Add some code

Add (BleMidiCentralService or BleMidiPeripheralService) and ServiceConnection field on the Activity or the Fragment.

    private BleMidiCentralService midiService = null;

    private final ServiceConnection serviceConnection = new ServiceConnection(){
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            midiService = ((BleMidiCentralService.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, BleMidiCentralService.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, BleMidiCentralService.class));

        ...
    }

Use Service methods

Service has these methods to use BLE 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.

BleMidiCentralService has these methods to scan BLE MIDI devices.

  • startScanDevice
    • Starts to scan BLE devices.
  • stopScanDevice
    • Stops to scan devices.

BleMidiPeripheralService has these methods to pretend as BLE MIDI device.

  • startAdvertising
    • Starts to advertise as BLE MIDI device.
  • stopAdvertising
    • Stops to advertise as BLE MIDI device.