Android Question Activate flash using wifi

Isac

Active Member
Licensed User
Longtime User
In this tutorial https://www.b4x.com/android/forum/t...dio-streaming-over-wifi-or-bluetooth.30648/it used the wifi or bluetooth to share sound, now let me see if you can turn on and turn off the flash.
eg: with my smartphone I would turn on the flash of another smartphone via WiFi.

I tried to use this library https://www.b4x.com/android/forum/t...va-code-inside-the-b4a-project.48367/#content but it does not work with wifi


B4X:
Public Sub SendAudio
    Log(mf.TurnFlashOn(True)) <--------------
    audioStream.StartRecording
    sendingAudio = True
End Sub

Public Sub StopSendingAudio
    Log(mf.TurnFlash(Off)) <------------------
    audioStream.StopRecording
    sendingAudio = False
   
End Sub
 

Johan Schoeman

Expert
Licensed User
Longtime User
In this tutorial https://www.b4x.com/android/forum/t...dio-streaming-over-wifi-or-bluetooth.30648/it used the wifi or bluetooth to share sound, now let me see if you can turn on and turn off the flash.
eg: with my smartphone I would turn on the flash of another smartphone via WiFi.

I tried to use this library https://www.b4x.com/android/forum/t...va-code-inside-the-b4a-project.48367/#content but it does not work with wifi


B4X:
Public Sub SendAudio
    Log(mf.TurnFlashOn(True)) <--------------
    audioStream.StartRecording
    sendingAudio = True
End Sub

Public Sub StopSendingAudio
    Log(mf.TurnFlash(Off)) <------------------
    audioStream.StopRecording
    sendingAudio = False
  
End Sub
Have you added the camera and flash permissions to your project's manifest file?
 
Upvote 0

Isac

Active Member
Licensed User
Longtime User
Main

I tried it and it works only on the single device
but I can not control it by bluetooth or wifi

B4X:
#Region  Project Attributes
    #ApplicationLabel: Walkie Talkie
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: portrait
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    Private admin As BluetoothAdmin
    Private btDevices As List
    Type NameAndMac (name As String, mac As String)
    Private searchInProgress As Boolean
    Private ip As String
    Dim mf As flash1
End Sub

Sub Globals
  
    Dim btnConnectWifi As Button
    Dim lblIP As Label
    Dim spnrPairedDevices As Spinner
    Dim edtIP As EditText
    Dim btnConnectBT As Button
    Dim lblWifiStatus As Label
    Dim lblBTStatus As Label
    Dim IME As IME
    Dim btnMakeDiscoverable As Button
    Dim btnBTSearch As Button
    Dim lblPTT As Label
    Private Button1 As Button
    Private Button2 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        StartService(Connector)
        btDevices.Initialize
        admin.Initialize("Admin")
      
        'add the already paired devices to the list
        'later the user can search for new devices
        Dim serial1 As Serial
        serial1.Initialize("")
        Dim pairedDevices As Map = serial1.GetPairedDevices
        For i = 0 To pairedDevices.Size - 1
            Dim nm As NameAndMac
            nm.Initialize
            nm.mac = pairedDevices.GetValueAt(i)
            nm.name = pairedDevices.GetKeyAt(i)
            btDevices.Add(nm)
        Next
    End If
    IME.Initialize("")
    Activity.LoadLayout("1")
    Activity.AddMenuItem("Disconnect", "mnuDisconnect")
    'filter for ip address (allow multiple dots)
    IME.SetCustomFilter(edtIP, edtIP.INPUT_TYPE_DECIMAL_NUMBERS, "0123456789.")
End Sub

Sub Activity_Resume
    edtIP.Text = ip
    spnrPairedDevices.Clear
    For Each nm As NameAndMac In btDevices
        spnrPairedDevices.Add(nm.name)
    Next
    'try to turn on Bluetooth if it is disabled
    If admin.IsEnabled = False Then
        If admin.Enable = False Then
            ToastMessageShow("Error enabling Bluetooth adapter.", True)
        Else
            ToastMessageShow("Enabling Bluetooth adapter...", False)
            'the StateChanged event will be soon raised
        End If
    End If
    UpdateUI
End Sub

Sub mnuDisconnect_Click
    CallSub(Connector, "Disconnect")
End Sub



Sub Activity_Pause (UserClosed As Boolean)
    'save the ip address
    ip = edtIP.Text
End Sub

Sub Admin_StateChanged (NewState As Int, OldState As Int)
    UpdateUI
End Sub

Public Sub UpdateUI
    'this sub is responsible for updating the UI based on the state which is stored in the service
    Dim wifi = True, bt = True, discover = True As Boolean
    If admin.IsEnabled = False Then
        bt = False
        discover = False
    End If
    lblIP.Text = Connector.MyIP
    lblWifiStatus.Text = Connector.WifiStatus
    lblBTStatus.Text = Connector.BTStatus
    If Connector.WifiConnected Then lblWifiStatus.TextColor = Colors.Green Else lblWifiStatus.TextColor = Colors.Red
    If Connector.BTConnected Then lblBTStatus.TextColor = Colors.Green Else lblBTStatus.TextColor = Colors.Red
    If spnrPairedDevices.Size = 0 Then bt = False
    If Connector.BTConnected Or Connector.WifiConnected Then
        wifi = False
        bt = False
        discover = False
    End If
  
    If wifi And Regex.IsMatch("[^.]+\.[^.]+\.[^.]+\.[^.]+", edtIP.Text) = False Then
        wifi = False
    End If
    If Connector.MyIP.Length = 0 Or Connector.MyIP = "127.0.0.1" Then
        wifi = False
    End If
    If searchInProgress Then bt = False
    btnConnectBT.Enabled = bt
    btnConnectWifi.Enabled = wifi
    btnBTSearch.Enabled = discover
    btnMakeDiscoverable.Enabled = discover
    lblPTT.Visible = Connector.BTConnected Or Connector.WifiConnected
End Sub

Sub btnConnectWifi_Click
    CallSubDelayed2(Connector, "ConnectWifi", edtIP.Text)
End Sub

Sub btnConnectBT_Click
    If spnrPairedDevices.SelectedIndex = -1 Then Return
    Dim nm As NameAndMac = btDevices.Get(spnrPairedDevices.SelectedIndex)
    CallSubDelayed2(Connector, "ConnectBT", nm.mac)
End Sub

'starts a search process
Sub btnBTSearch_Click
    spnrPairedDevices.Clear
    btDevices.Clear
    If admin.StartDiscovery    = False Then
        ToastMessageShow("Error starting discovery process.", True)
    Else
        searchInProgress = True
        SetBTStatus("Searching for BT devices...")
        UpdateUI
    End If
End Sub

Sub SetBTStatus(status As String)
    Connector.BTstatus = status
    lblBTStatus.Text = status
End Sub

Sub Admin_DiscoveryFinished
    searchInProgress = False
    If spnrPairedDevices.Size = 0 Then
        SetBTStatus("No BT devices found.")
    Else
        SetBTStatus(spnrPairedDevices.Size & " device(s) found.")
    End If
    UpdateUI
End Sub

Sub Admin_DeviceFound (Name As String, MacAddress As String)
    Log(Name & ":" & MacAddress)
    spnrPairedDevices.Add(Name)
    Dim nm As NameAndMac
    nm.Initialize
    nm.Name = Name
    nm.mac = MacAddress
    btDevices.Add(nm)
    SetBTStatus("Searching for devices (" & btDevices.Size & " found)")
End Sub

Sub btnMakeDiscoverable_Click
    'this intent makes the device discoverable for 300 seconds.
    Dim i As Intent
    i.Initialize("android.bluetooth.adapter.action.REQUEST_DISCOVERABLE", "")
    i.PutExtra("android.bluetooth.adapter.extra.DISCOVERABLE_DURATION", 300)
    StartActivity(i)
End Sub

Sub edtIP_TextChanged (Old As String, New As String)
    UpdateUI 'the btnConnectWifi.Enabled depends on the text
End Sub


Sub Activity_Touch (Action As Int, X As Float, Y As Float)
    If Connector.BTConnected = False And Connector.WifiConnected = False Then Return
    If Action = Activity.ACTION_DOWN Then
        Activity.Color = Colors.Red
        CallSub(Connector, "SendAudio")
    Else If Action = Activity.ACTION_UP Then
        Activity.Color = Colors.Black
        CallSub(Connector, "StopSendingAudio")
    End If
End Sub

Sub Button1_Click
    CallSub(Connector,"torciaon")
End Sub





Sub Button2_Click
  
    CallSub(Connector,"torciaoff")
  
  
End Sub


Connector

B4X:
#Region Service Attributes
#StartAtBoot: False
#End Region

Sub Process_Globals
Public MyIP As String = "N/A"
Public WifiStatus As String = "Disconnected"
Public BTStatus As String = "Disconnected"
Public WifiConnected, BTConnected As Boolean
Private admin As BluetoothAdmin
Private serial1 As Serial
Private socket1 As Socket
Private server As ServerSocket
Private port As Int = 21341
Private uuid As String = "dabcabcd-afac-11de-8a39-0800200c9a6"
Private astream As AsyncStreams
Private pe As PhoneEvents
Private audioStream As AudioStreamer
Private sendingAudio As Boolean
End Sub

Sub Service_Create
'start listening for BT and wifi connections
server.Initialize(port, "server")
Try
server.Listen
Catch
WifiStatus = "Error listening: " & LastException
UpdateUI
End Try
admin.Initialize("admin")
serial1.Initialize("serial1")
If serial1.IsEnabled Then serial1.Listen2("na", uuid)
pe.Initialize("pe")
pe_ConnectivityChanged("", "", Null)
audioStream.Initialize("AudioStream", 22050, True, 16, audioStream.VOLUME_MUSIC)
End Sub

Sub admin_StateChanged (NewState As Int, OldState As Int)
If NewState = admin.STATE_ON Then serial1.Listen2("na", uuid)
End Sub

Sub pe_ConnectivityChanged (NetworkType As String, State As String, Intent As Intent)
MyIP = server.GetMyWifiIP
UpdateUI
End Sub

Sub Service_Start (StartingIntent As Intent)

End Sub
Private Sub UpdateUI
CallSub(Main, "UpdateUI")
End Sub

Public Sub Disconnect
If WifiConnected Or BTConnected Then
astream.Close
AStream_Terminated
End If
End Sub
Public Sub ConnectBT(Address As String)
serial1.Connect2(Address, uuid)
BTStatus = "Trying to connect..."
UpdateUI
End Sub

Public Sub ConnectWifi(Ip As String)
socket1.Initialize("socket1")
socket1.Connect(Ip, port, 30000)
WifiStatus = "Trying to connect..."
UpdateUI
End Sub



Private Sub socket1_Connected (Successful As Boolean)
'client connected to server
If Successful Then
WifiConnected = True
StartAStream(socket1.InputStream, socket1.OutputStream)
WifiStatus = "Connected"
Else
WifiStatus = "Error: " & LastException
End If
UpdateUI
End Sub

Private Sub server_NewConnection (Successful As Boolean, NewSocket As Socket)
'server accepted client
If Successful Then
WifiConnected = True
StartAStream(NewSocket.InputStream, NewSocket.OutputStream)
WifiStatus = "Connected"
Else
WifiStatus = "Error: " & LastException
End If
UpdateUI
server.Listen
End Sub

Private Sub serial1_Connected (Success As Boolean)
If Success Then
BTStatus = "Connected"
BTConnected = True
StartAStream(serial1.InputStream, serial1.OutputStream)
Else
BTStatus = "Error: " & LastException.Message
End If
UpdateUI
End Sub

Private Sub StartAStream (In As InputStream, out As OutputStream)
Log("StartAStream")
astream.InitializePrefix(In, True, out, "astream")
'call StartPlaying so the audio streamer will be ready to receive audio data
audioStream.StartPlaying
End Sub

Public Sub torciaon
Log(Main.mf.TurnFlashOn(True))
End Sub

Public Sub torciaoff
Log(Main.mf.TurnFlashOff)
End Sub


Public Sub SendAudio

audioStream.StartRecording
sendingAudio = True
End Sub

Public Sub StopSendingAudio

audioStream.StopRecording
sendingAudio = False
End Sub


Sub AudioStream_RecordBuffer (Data() As Byte)
If sendingAudio Then
astream.Write(Data)
End If
End Sub

Sub astream_NewData (Buffer() As Byte)
If sendingAudio = False Then
'play the received audio data
audioStream.Write(Buffer)
End If
End Sub


Sub Astream_Error
Log("Error: " & LastException)
astream.Close
AStream_Terminated 'manually call this method as it will not be called
'when we explicitly close the connection.
End Sub
Sub AStream_Terminated

If BTConnected Then
BTStatus = "Disconnected"
Else If WifiConnected Then
WifiStatus = "Disconnected"
End If
BTConnected = False
WifiConnected = False
audioStream.StopPlaying
audioStream.StopRecording
UpdateUI
End Sub

Sub Service_Destroy

End Sub


Manifest Editor

B4X:
'This code will be applied to the manifest file during compilation.
    'You do not need to modify it in most cases.
    'See this link for for more information: http://www.b4x.com/forum/showthread.php?p=78136
    AddManifestText(
    <uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14"/>
    <supports-screens android:largeScreens="true"
    android:normalScreens="true"
    android:smallScreens="true"
    android:anyDensity="true"/>)
    AddManifestText(<uses-feature android:name="android.hardware.telephony" android:required="false" />)
    AddPermission("android.permission.ACCESS_COARSE_LOCATION")
    AddPermission("android.permission.INTERNET")
    AddPermission("android.permission.ACCESS_FINE_LOCATION")
    AddPermission("android.permission.ACCESS_COARSE_UPDATES")
    AddPermission("android.permission.READ_PHONE_STATE")
    AddPermission("android.permission.VIBRATE")
    AddPermission("android.permission.CAMERA")
    AddManifestText(uses-feature android:name="android.hardware.camera" />)
    AddPermission("android.permission.FLASHLIGHT")
    AddManifestText(<uses-feature android:name="android.hardware.camera.flash" android:required="false" />)
    AddPermission("android.hardware.camera")
    SetApplicationAttribute(android:icon, "@drawable/icon")
    SetApplicationAttribute(android:label, "$LABEL$")
    'End of default text.
 
Upvote 0

Johan Schoeman

Expert
Licensed User
Longtime User
In this tutorial https://www.b4x.com/android/forum/t...dio-streaming-over-wifi-or-bluetooth.30648/it used the wifi or bluetooth to share sound, now let me see if you can turn on and turn off the flash.
eg: with my smartphone I would turn on the flash of another smartphone via WiFi.

I tried to use this library https://www.b4x.com/android/forum/t...va-code-inside-the-b4a-project.48367/#content but it does not work with wifi


B4X:
Public Sub SendAudio
    Log(mf.TurnFlashOn(True)) <--------------
    audioStream.StartRecording
    sendingAudio = True
End Sub

Public Sub StopSendingAudio
    Log(mf.TurnFlash(Off)) <------------------
    audioStream.StopRecording
    sendingAudio = False
 
End Sub
A fully working example attached. There are 2 library files in the /Files folder of the attached B4A project (FiddleAround.jar / xml). Copy them to your additional library folder. The receiving device's torch will be switched on - the sending device's torch will be switched off. If you want to switch off the torch then just click briefly on the Push To Talk button.

Install the same B4A project on both / more devices.

Only 3 lines of code that was added to the service of @Erel's original project (with of course my FiddleAround library enabled)

Enjoy!
 

Attachments

  • IsacTorchSpecial.zip
    71.1 KB · Views: 248
Last edited:
Upvote 0
Top