我在Android上使用播放音频的前台服务。我还通过 NDK 从 Android 双簧管库在与服务无关的片段上使用麦克风输入。但是,在我关闭应用程序后,即使服务被终止(服务通知消失(,麦克风也无法访问其他应用程序。
以下是我启动服务的方式:
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);
}
}
服务只是public class MainService extends Service
我在AndroidManifest
上添加了这个
<service android:name=".services.MainService" android:stopWithTask="true"/>
所以当我关闭应用程序时它会停止。
但是,双簧管代码不在服务中。我怀疑C++在后台保持线程打开。不知何故,即使在应用程序关闭后,此线程仍然存在。可能吗?
我添加了这个:
override fun onDestroy() {
Log.d(TAG, "-----fxfragment destroyed!")
NativeInterface.destroyAudioEngine()
super.onDestroy()
}
以删除C++端的音频引擎。它适用于某些手机,麦克风是可用的。但在某些方面,事实并非如此。
在 onResume 中创建引擎并在 onPause(( 中销毁,以便流保留独占 模式仅在对焦时。这允许其他应用回收独占流模式。因此,我建议您添加onResume((和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);
}
并在 onPause(( 中
@Override
protected void onPause() {
if (mLatencyUpdater != null) mLatencyUpdater.cancel();
PlaybackEngine.delete();
super.onPause();
}
您也可以通过此github链接了解更多详情
这是库中的错误,正如这里提到的库问题链接