PPP
PPP

Reputation: 1850

Android foreground service holds microphone access even after being killed

I'm using a foreground service on Android that plays audio. I also use microphone input through NDK from Android Oboe library on a fragment, unrelated to the service. However, after I close the app, the microphone is inacessible to other apps, even if the service is killed (the service notification goes away).

Here's how I'm starting the service:

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

                //Start in Foreground
                ContextCompat.startForegroundService(this, intent);

                if (serviceConnection != null) {
                    //Then bind service
                    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                }
            } else {
                startService(intent);
                if (serviceConnection != null) {
                    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
                }
            }

The service is just public class MainService extends Service

and I added this on AndroidManifest

<service android:name=".services.MainService" android:stopWithTask="true"/>

so it stops when I close the app.

However, the oboe code is not in the service. I suspect that C++ keeps a thread open on the background. Somehow, this thread lives even after the app closes. Is it possible?

I added this:

   override fun onDestroy() {
        Log.d(TAG, "-----fxfragment destroyed!")
        NativeInterface.destroyAudioEngine()
        super.onDestroy()
    }

to delete the audio engine on the C++ side. It works on some phones, the microphone is acessible. But on some, it does not.

Upvotes: 1

Views: 859

Answers (2)

Zia
Zia

Reputation: 195

Creating engine in onResume and destroying in onPause() so the stream retains exclusive mode only while in focus. This allows other apps to reclaim exclusive stream mode. Therefore, I would recommend you to add onResume() and onPause()

@Override
protected void onResume() {
    super.onResume();
    PlaybackEngine.create(this);
    setupLatencyUpdater();
    // Return the spinner states to their default value
    mChannelCountSpinner.setSelection(CHANNEL_COUNT_DEFAULT_OPTION_INDEX);
    mPlaybackDeviceSpinner.setSelection(SPINNER_DEFAULT_OPTION_INDEX);
    mBufferSizeSpinner.setSelection(SPINNER_DEFAULT_OPTION_INDEX);
    mAudioApiSpinner.setSelection(SPINNER_DEFAULT_OPTION_INDEX);
}

and in the onPause()

@Override
protected void onPause() {
   if (mLatencyUpdater != null) mLatencyUpdater.cancel();
   PlaybackEngine.delete();
   super.onPause();
}

You can also go through this github link for further details

Upvotes: 1

Mayur Dabhi
Mayur Dabhi

Reputation: 3926

this is bug in library as mention here library issues link

Upvotes: 0

Related Questions