Android Question Problem detecting if paired bluetooth has been disconnected

Status
Not open for further replies.

Roy Raymundo

Member
Licensed User
My b4a program connects to a device that has a hardware and that hardware has bluetooth device. It turns appliances on/off via click of a button through bluetooth or sms, whichever the user selects. It's ok with bluetooth. I just want to make it error proof. What I did is my b4a program connected successfully to the hardware that has bluetooth device. After that, then I turned the hardware off. My variable Var.BT_Service_connected must then become false after I turned off the hardware but how come it is still evaluated as true in my code even though I turned off the hardware to which my bluetooth program is connected. What happened is that it still execute:

tmrSend.Enabled =True
ProgressDialogShow("Processing Request...")

Since the hardware is turned off, it makes my program crash and stop running. And how come the Try Catch failed to catch the error and allowed my program to crashed?

These are the code fragments:

If Var.sendMode =1 AND Var.BT_Service_connected = True Then
Try
tmrSend.Enabled =True
ProgressDialogShow("Processing Request...")
Catch
Msgbox("Error sending Bluetooth message!", "Error Sendindg")
ReverseButton
End Try
End If

This is my svc_bt_connected:


Sub Process_Globals

End Sub
Sub Service_Create
'Var.BT_Service_connected = False
End Sub

Sub Service_Start (StartingIntent As Intent)
If StartingIntent.Action = "android.bluetooth.device.action.ACL_CONNECTED" Then
Log("BT_Connect")
Var.BT_Service_connected = True
End If

Log(StartingIntent)
Log(StartingIntent.ExtrasToString)

End Sub

Sub Service_Destroy

End Sub


This is my svc_bt_disconnect:
Sub Process_Globals

End Sub
Sub Service_Create

End Sub

Sub Service_Start (StartingIntent As Intent)
If StartingIntent.Action = "android.bluetooth.device.action.ACL_DISCONNECTED" Then
Log("BT_Disconnect")
Var.BT_Service_connected = False
End If
Log(StartingIntent)
Log(StartingIntent.ExtrasToString)

End Sub

Sub Service_Destroy

End Sub

This is my Manifest:
AddManifestText(
<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="14"/>
<supports-screens android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="true"
android:anyDensity="true"/>)

AddReceiverText(svc_bt_disconnect, <intent-filter> <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/></intent-filter>)
AddReceiverText(svc_bt_connected, <intent-filter> <action android:name="android.bluetooth.device.action.ACL_CONNECTED"/></intent-filter>)
AddPermission(android.permission.BLUETOOTH)

SetApplicationAttribute(android:icon, "@drawable/icon")
SetApplicationAttribute(android:label, "$LABEL$")

And this is my BTService:
Sub Process_Globals
Dim AStream As AsyncStreams
Dim MsgToSend As String
Dim MsgReceived As String
End Sub

Sub Service_Create

End Sub

Sub Service_Start (StartingIntent As Intent)
If AStream.IsInitialized Then AStream.Close
AStream.Initialize(Control.serial1.InputStream, Control.serial1.OutputStream, "AStream")
Log("Astream Initialized")
End Sub

Sub Service_Destroy
AStream.Close
End Sub

Sub SendMsgBluetooth
Log(MsgToSend)
If Var.BT_Service_connected = True Then
AStream.Write(MsgToSend.GetBytes("UTF8"))
End If
End Sub

Sub AStream_NewData(Buffer() As Byte)
Var.ErrorSend = False
Var.nagSuccess = True
Try
MsgReceived = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
If IsPaused(Control) = False Then
CallSub(Control, "NewMsgFrom")
End If
Catch
Msgbox("Error sending Bluetooth message!", "Error Sendindg")
End Try
End Sub

Sub AStream_Error
ToastMessageShow("Bluetooth Disconnected", True)
AStream.Close
AStream_Terminated
End Sub

Sub AStream_Terminated
Var.ErrorSend = True
Var.nagSuccess = False
'ToastMessageShow("Bluetooth Disconnected", True)
ProgressDialogHide
Msgbox("Error sending Bluetooth message!", "Error Sendindg")
CallSub(Control,"ReverseButton")
End Sub
 
Last edited:

Roy Raymundo

Member
Licensed User
Is Var.BT_Service_connected defined as global variable in your main, it should be.
I declared it inside a code module so that I can call that variable anywhere. Inside Sub Process Globals of a module. The module name is Var.
Dim BT_Service_connected As Boolean : BT_Service_connected = False
 

Jmu5667

Well-Known Member
Licensed User
Try this: since the svc_bt_disconnect only gets called when the device disconnects, call stopservice("") in the service_start, then in Service_Destroy set var.BT_Service_connected to False. This is the only code you need in this service, you don't need to check the intent string.
 

Roy Raymundo

Member
Licensed User
Try this: since the svc_bt_disconnect only gets called when the device disconnects, call stopservice("") in the service_start, then in Service_Destroy set var.BT_Service_connected to False. This is the only code you need in this service, you don't need to check the intent string.
Is this exactly what you intend me to do with svc_bt_disconnect? :

Sub Process_Globals
End Sub
Sub Service_Create
End Sub
Sub Service_Start (StartingIntent As Intent)
StopService("")
If StartingIntent.Action = "android.bluetooth.device.action.ACL_DISCONNECTED" Then
Log("BT_Disconnect")
Var.BT_Service_connected = False
End If
Log(StartingIntent)
Log(StartingIntent.ExtrasToString)
End Sub
Sub Service_Destroy
Var.BT_Service_connected = False
End Sub
 

Jmu5667

Well-Known Member
Licensed User
put his in your manifest

' // BlueTooth intents
AddReceiverText(svc_bt_state, <intent-filter> <action android:name="android.bluetooth.adapter.action.STATE_CHANGED"/></intent-filter>)
AddReceiverText(svc_bt_disconnect, <intent-filter> <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/></intent-filter>)
AddReceiverText(svc_bt_connected, <intent-filter> <action android:name="android.bluetooth.device.action.ACL_CONNECTED"/></intent-filter>)

svc_bt_state

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

Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub
Sub Service_Create

     log("svc_bt_state(), Service_Create")
  
End Sub

Sub Service_Start (StartingIntent As Intent)

   log("svc_bt_state(), Service_Start, Intent=" & StartingIntent.Action)
   If StartingIntent.ExtrasToString <> "" Then
    
      log("svc_bt_state(), Service_Start, Extras=" & StartingIntent.ExtrasToString)
    
     ' // off
     If StartingIntent.GetExtra("android.bluetooth.adapter.extra.STATE") = 10 Then
       log("svc_bt_state(), Service_Start, Bluetooth is OFF")          
       ' // schedule the serial service to start
       StartServiceAt(svc_serial,DateTime.Add(DateTime.Now + (DateTime.TicksPerSecond * 3) ,0,0,0), True)
      
     End If
     ' // on
     If StartingIntent.GetExtra("android.bluetooth.adapter.extra.STATE") = 12 Then
       log("svc_bt_state(), Service_Start, Bluetooth is ON")
     End If
    
   End If
  
   ' // no need to keep this alive
   StopService("")
  
End Sub

Sub Service_Destroy
  
   log("svc_bt_state(), Service_Destroy")
  
End Sub
svc_bt_disconnect

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

Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub
Sub Service_Create

   log("svc_bt_disconnect(), Service_Create")
  
End Sub

Sub Service_Start (StartingIntent As Intent)

   ' // BT Device is now disconnected
   log("svc_bt_disconnect(), Service_Start,Intent=" & StartingIntent.Action)
   If StartingIntent.ExtrasToString <> "" Then
     log("svc_bt_disconnect(), Service_Start,Extras=" & StartingIntent.ExtrasToString)
   End If
   StopService("")
  
End Sub

Sub Service_Destroy

   log("svc_bt_disconnect(), Service_Destroy")

End Sub
svc_bt_connected

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

Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub
Sub Service_Create
 
   log("svc_bt_connected(), Service_Create")
  
End Sub

Sub Service_Start (StartingIntent As Intent)

   log("svc_bt_connected(), Service_Start,Intent=" & StartingIntent.Action)
   If StartingIntent.ExtrasToString <> "" Then
     log("svc_bt_connected(), Service_Start,Extras=" & StartingIntent.ExtrasToString)
   End If
  
' // we can restart the svc_serial from here after we have been woken up
   If IsPaused(svc_serial) Then
     log("svc_bt_connected(), Service_Start, Starting svc_serial service")
     StartService(svc_serial)
   End If
   ' // no need to keep this alive
   StopService("")
  
End Sub

Sub Service_Destroy
  
   log("svc_bt_connected(), Service_Destroy")
  
End Sub

svc_serial should handle the actual serial comms with the BT device.

Regards

John
 

brunnlechner

Member
Licensed User
Hi
this works:

B4X:
Manifest:
AddReceiverText(s2, <intent-filter>
<action android:name="android.bluetooth.device.action.ACL_CONNECTED"/>
<action android:name="android.bluetooth.device.action.ACL_DISCONNECTED"/>
</intent-filter>)
AddPermission(android.permission.BLUETOOTH)
Service s2:
B4X:
Sub Service_Start (StartingIntent As Intent)
    If StartingIntent.Action = "android.bluetooth.device.action.ACL_CONNECTED" Then
        Log("BT_Connect")
        ToastMessageShow("BT_Connect"&StartingIntent,True)
    Else If StartingIntent.Action = "android.bluetooth.device.action.ACL_DISCONNECTED" Then
        Log("BT_Disconnect")
        ToastMessageShow("BT_Disconnect"&StartingIntent,True)
    End If
End Sub
 

Marcob

Member
Licensed User
I've found a nice way to check audio Bluetooth connection:

B4X:
Sub IsBluetoothConnected As Boolean
    Dim r As Reflector
    r.Target = r.GetContext
    r.Target = r.RunMethod2("getSystemService", "audio", "java.lang.String")
    Return r.RunMethod("isBluetoothA2dpOn")   
End Sub
- No additional service or manifest addition required
- More responsive
 
Status
Not open for further replies.
Top