Android Question Check microphone

GvD

Member
Licensed User
Longtime User
is it possible to determine whether the microphone is already switched on or in use by an other application?
 

Peter Simpson

Expert
Licensed User
Longtime User
is it possible to determine whether the microphone is already switched on or in use by an other application?

Try this,
Try this:
Sub Class_Globals
    Private Root As B4XView
    Private XUI As XUI
End Sub

Public Sub Initialize
'    B4XPages.GetManager.LogEvents = True
End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Private Sub Button1_Click
    Dim AudioManager As JavaObject
        AudioManager.InitializeContext
        AudioManager = AudioManager.RunMethod("getSystemService", Array("audio"))
    Dim Mode As Int = AudioManager.RunMethod("getMode", Null)
  
    If Mode = 3 Or Mode = 2 Then ' MODE_IN_COMMUNICATION = 3, MODE_IN_CALL = 2
        Log(True)
    Else
        Log(False)
    End If
End Sub


Enjoy...
 
Upvote 0

Peter Simpson

Expert
Licensed User
Longtime User
Hello,
is it possible to determine whether the microphone is already switched on or in use by an other application?
Here are my test results

Test results:
Logger connected to:  Google Pixel 7 Pro
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
Call B4XPages.GetManager.LogEvents = True to enable logging B4XPages events.
** Activity (main) Resume **
false
** Activity (main) Pause event (activity is not paused). **
** Activity (main) Resume **
true
** Activity (main) Pause event (activity is not paused). **

First I ran the test app and pressed the button with the code, the result was false as it should be, the mic is not being used. I then rang by business phone via WhatsApp from my test phone, with WhatsApp connected I went back to the test app and pressed the button with the code again, the result was true as it should be as the mic is being used by WhatsApp. I also get the exact same result if I just call my business phone normally via my test phones normal number pad.

I can't say much more than that.


Enjoy...
 
Last edited:
Upvote 0

GvD

Member
Licensed User
Longtime User
i use an
Version _250118_151418:
#Region Shared Files
#CustomBuildAction: folders ready, %WINDIR%\System32\Robocopy.exe,"..\..\Shared Files" "..\Files"
'Ctrl + click to sync files: ide://run?file=%WINDIR%\System32\Robocopy.exe&args=..\..\Shared+Files&args=..\Files&FilesSync=True
#End Region

'Ctrl + click to export as zip: ide://run?File=%B4X%\Zipper.jar&Args=Project.zip

Sub Class_Globals
    Private Root As B4XView
    Private xui As XUI
    Private rp As RuntimePermissions
End Sub

Public Sub Initialize
    ' auskommentieren, wenn's läuft
  B4XPages.GetManager.LogEvents = True

End Sub

'This event will be called once, before the page becomes visible.
Private Sub B4XPage_Created (Root1 As B4XView)
    Root = Root1
    Root.LoadLayout("MainPage")
    RequestMicrophonePermission
End Sub

'You can see the list of page related events in the B4XPagesManager object. The event name is B4XPage.

Private Sub Button1_Click
    StartTesting
    
End Sub

Sub StartTesting
    For x = 1 To 30
        CheckIt
        'CheckMicrophoneUsage        ' nur für Android ab Version 29
        CheckMicrophoneUsageOldAndroid
        CheckMicrophoneUsageDirect
        CheckMicrophoneUsageDirectV2
        Sleep(1000)
        Log( (x) & "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    Next
End Sub

Private Sub Button2_Click
    Log("Bye")
    ExitApplication
End Sub

Private Sub CheckIt
    Dim AudioManager As JavaObject
    AudioManager.InitializeContext
    AudioManager = AudioManager.RunMethod("getSystemService", Array("audio"))
    Dim Mode As Int = AudioManager.RunMethod("getMode", Null)
 
    If Mode = 3 Or Mode = 2 Then ' MODE_IN_COMMUNICATION = 3, MODE_IN_CALL = 2
        Log("CheckIT: Possibly mobile is aktive")
    Else
        Log("CheckIT: No activity detectable")
    End If
    
End Sub

Private Sub CheckMicrophoneUsageOldAndroid
    Try
        Dim AudioRecord As JavaObject
        Dim sampleRate As Int = 44100
        Dim channelConfig As Int = 16 ' CHANNEL_IN_MONO
        Dim audioFormat As Int = 2 ' ENCODING_PCM_16BIT
        Dim bufferSize As Int = AudioRecord.RunMethod("getMinBufferSize", Array(sampleRate, channelConfig, audioFormat))
        AudioRecord = AudioRecord.InitializeNewInstance("android.media.AudioRecord", Array(1, sampleRate, channelConfig, audioFormat, bufferSize)) ' AUDIO_SOURCE_MIC = 1
        AudioRecord.RunMethod("startRecording", Null)

        Dim state As Int = AudioRecord.RunMethod("getRecordingState", Null)
        If state = 3 Then ' RECORDSTATE_RECORDING = 3
            Log("OldAndroid: The microphone is currently in use!")
        Else
            Log("OldAndroid: Microphone is not active.")
        End If

        AudioRecord.RunMethod("stop", Null)
        AudioRecord.RunMethod("release", Null)
    Catch
        'Log("OldAndroid: Fehler beim Zugriff auf das Mikrofon. Es könnte von einer anderen App verwendet werden.")
        Log("OldAndroid: Error accessing the microphone. It could be used by another app.")
    End Try
    
End Sub

Private Sub CheckMicrophoneUsage
    ' Empfohlene Methode für API 29+ / Recommended method for API 29+
    Dim AudioManager As JavaObject
    AudioManager.InitializeContext
    AudioManager = AudioManager.RunMethod("getSystemService", Array("audio"))

    Dim isRecording As Boolean = AudioManager.RunMethod("isRecording", Null)
    If isRecording Then
        Log("CheckMicrophoneUsage: The microphone is currently in use!")
    Else
        Log("CheckMicrophoneUsage: Microphone is not active.")
    End If
End Sub


Private Sub CheckMicrophoneUsageDirect
    ' direkter Test des Zugriffs
    Try
        Dim AudioRecord As JavaObject
        Dim sampleRate As Int = 44100
        Dim channelConfig As Int = 16 ' CHANNEL_IN_MONO
        Dim audioFormat As Int = 2 ' ENCODING_PCM_16BIT
        Dim bufferSize As Int = AudioRecord.RunMethod("getMinBufferSize", Array(sampleRate, channelConfig, audioFormat))
        AudioRecord = AudioRecord.InitializeNewInstance("android.media.AudioRecord", Array(1, sampleRate, channelConfig, audioFormat, bufferSize)) ' AUDIO_SOURCE_MIC = 1
        AudioRecord.RunMethod("startRecording", Null)

        Dim state As Int = AudioRecord.RunMethod("getRecordingState", Null)
        If state = 3 Then ' RECORDSTATE_RECORDING = 3
                    Log("Direct: Microphone is actively used.")
        Else
                    Log("Direct:  Microphone is not active.")
        End If

        AudioRecord.RunMethod("stop", Null)
        AudioRecord.RunMethod("release", Null)
    Catch
            'Log("Direct: Fehler beim Zugriff auf das Mikrofon. Es könnte von einer anderen App verwendet werden.")
            Log("Direct: Error accessing the microphone. It could be used by another app.")
    End Try
End Sub

Private Sub CheckMicrophoneUsageDirectV2
    Try
        ' Verwenden von AudioManager, um den Mikrofonstatus zu prüfen
        Dim AudioManager As JavaObject
        AudioManager.InitializeContext
        AudioManager = AudioManager.RunMethod("getSystemService", Array("audio"))

        ' Holen des Modus des Systems
        Dim Mode As Int = AudioManager.RunMethod("getMode", Null)
        
        ' Prüfen, ob das Mikrofon in einem aktiven Modus ist
        If Mode = 3 Or Mode = 2 Then ' 3 = MODE_IN_COMMUNICATION, 2 = MODE_IN_CALL
                    'Log("DirectV2: Mikrofon wird aktiv verwendet (Telefonie oder Kommunikation).")
                    Log("DirectV2: Microphone is actively used (telephony or communication).")
        Else
                    'Log("DirectV2: Mikrofon wird nicht aktiv verwendet.")
                    Log("DirectV2: Microphone is not actively used.")
        End If
    Catch
            'Log("DirectV2: Fehler beim Abrufen des Mikrofonstatus.")
            Log("DirectV2: Error when retrieving the microphone status.")
    End Try
End Sub



' Runtime-Berechtigung anfragen
Private Sub RequestMicrophonePermission
    Log("Check authorisation...")
    ' Überprüfe, ob die Berechtigung bereits erteilt wurde
    If rp.Check(rp.PERMISSION_RECORD_AUDIO) = False Then
        ' Fordere die Berechtigung an, wenn sie noch nicht erteilt wurde
        rp.CheckAndRequest(rp.PERMISSION_RECORD_AUDIO)
        ' Warte auf das Ergebnis der Berechtigungsabfrage
        Wait For Activity_PermissionResult (Permission As String, Result As Boolean)
        If Result Then
            'Log("Mikrofon-Berechtigung wurde gewährt.")
            Log("Mikrofon-Berechtigung wurde gewährt.")
        Else
            'Log("Mikrofon-Berechtigung wurde verweigert.")
            Log("Microphone authorisation was denied.")
        End If
    Else
        'Log("Mikrofon-Berechtigung wurde bereits gewährt.")
        Log("Microphone authorisation has already been granted.")
    End If
End Sub
 
Upvote 0

GvD

Member
Licensed User
Longtime User
I use an Samsung Note 10 with Android version 12...


*** Logs ***

*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
*** mainpage: B4XPage_Created
Check authorisation...
Microphone authorisation has already been granted.
*** mainpage: B4XPage_Appear
** Activity (main) Resume **

###################################################################################
I used the ‘dictation machine’ between call 9 and 12 ~~~~ - but it was not recognised.
###################################################################################

9~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.
10~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.
11~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.
12~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.
13~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.


#########################################################################################
here i used the telephone between call 22 and 25 ~~~~ - it was recognised by Sub CheckIt
#########################################################################################

20~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.
21~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: No activity detectable
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is not actively used.
22~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: Possibly mobile is aktive
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is actively used (telephony or communication).
23~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: Possibly mobile is aktive
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is actively used (telephony or communication).
24~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CheckIT: Possibly mobile is aktive
OldAndroid: Error accessing the microphone. It could be used by another app.
Direct: Error accessing the microphone. It could be used by another app.
DirectV2: Microphone is actively used (telephony or communication).
25~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

any idea why it can only detect the phone call?
 
Upvote 0
Top