Android Question Will somebody Help Me Solve this issue of Bluetooth Service.

jahswant

Well-Known Member
Licensed User
Longtime User
This is my service code i want to reconnect automatically when my device disconnects.I'm tired I'm trying on it since a week.
B4X:
#Region  Project Attributes
    #ApplicationLabel: BTServer
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#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 Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    StartService(BTService)

End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub
Sub UpdateUi
    If BTService.btConnected = True Then
    Log("Connected")
    Else
    Log("Not Connected")
    End If
End Sub
What is wrong with this ? doesn't solve my issue.
 

ilan

Expert
Licensed User
Longtime User
Upvote 0

jahswant

Well-Known Member
Licensed User
Longtime User
Thanks Ilan for your answer this is my service insted
B4X:
#Region  Service Attributes
    #StartAtBoot: False
    #StartCommandReturnValue: android.app.Service.START_STICKY
#End Region

Sub Process_Globals
   Dim BT As BluetoothAdmin
   Dim Serial1 As Serial
   Dim btConnected As Boolean
   Private ast As AsyncStreamsText
   Dim MyDeviceName As String
   Dim Notification1 As Notification
   Dim ServiceMessage As String
   Dim foundDevices As List
   Type NameAndMaco (Name As String, Mac As String)
   Dim connectedDevice As NameAndMaco
   Dim Tim As Timer
End Sub

Sub FindDevices
Log("FindDevices")
     foundDevices.Initialize
    If BT.StartDiscovery    = False Then
        ToastMessageShow("Error starting discovery process.", True)
    Else
        Log("Searching for devices...")
    End If
End Sub

Sub Tim_Tick
    FindDevices
End Sub


Sub Service_Create
    foundDevices.Initialize
   Tim.Initialize("Tim",10000)
   Tim.Enabled = False
   MyDeviceName = "ALCATEL ONE TOUCH POP7"  'Put the name of your coupled device here!
   ToastMessageShow("Trying to connect to " & MyDeviceName, True)

   Try
      BT.Initialize("BT")
      Serial1.Initialize("Serial1")
   Catch
      ToastMessageShow("No BlueTooth Device visible...", True)
   End Try
    
          'Start Bluetooth
      Try
         If BT.IsEnabled = False Then
            BT.Enable
         Else
            'connect to device
          
            BTConnectToDevice 
      
         End If
      Catch
      Log(LastException.Message)
      End Try

    Notification1.Initialize
    Notification1.Icon = "icon" 'use the application icon file for the notification
End Sub

Sub Service_Start (StartingIntent As Intent)
    ServiceMessage="Door Service"
    Notification1.SetInfo(ServiceMessage,ServiceMessage & "  Is Running", Main)
    Notification1.Sound = False
    'Make sure that the process is not killed during the download
    'This is important if the download is expected to be long.
    'This will also show the status bar notification
    Service.StartForeground(1, Notification1)
    Log("service running")
End Sub

Sub Service_Destroy

End Sub

Sub BT_DiscoveryFinished
    Log("In Admin_DiscoveryFinished")
    If foundDevices.Size < 1 Then
        Log("No device found.")
    Else
        Dim l As List
        Dim Mac As List
        l.Initialize
        Mac.Initialize
        For i = 0 To foundDevices.Size - 1
            Dim nm As NameAndMaco
            nm = foundDevices.Get(i)
            l.Add(nm.Name)
            Mac.Add(nm.Mac)
        Next
    End If
Tim.Enabled = False
End Sub

Sub BT_DeviceFound (Name As String, MacAddress As String)
    Log("Admin_DeviceFound")
    Log(Name & ":" & MacAddress)
    Dim nm As NameAndMaco
    nm.Name = Name
    nm.Mac = MacAddress
    foundDevices.Add(nm)
    If foundDevices.Size = 0 Then
    Log("No Device Found")
    Else
    Log("Trying to connect to: " & connectedDevice.Name & " (" & connectedDevice.Mac & ")")
    BTConnectToDevice
    Tim.Enabled = False
    Log("Devices Found")
    End If
End Sub

Sub BT_StateChanged(NewState As Int,OldState As Int)
Log("BT_StateChanged")
   If NewState = BT.STATE_ON Then
      Log("BT Enabled")
   Else
      Serial1.Disconnect
      'timBT.Enabled = False
      Log("BT Not Enabled")
      If IsPaused(Main) Then
        Notification1.Sound = True
        Notification1.SetInfo("Bluetooth Did Not Connect to " & Serial1.Address, " broken!", Main)
        Notification1.AutoCancel = True
        Notification1.Notify(1)
    End If
   End If
End Sub
Sub BTConnectToDevice
Log("BTConnectToDevice")
   Dim PairedDevices As Map

   PairedDevices = Serial1.GetPairedDevices
   Try
      Serial1.Connect3(PairedDevices.Get(MyDeviceName),1)
   Catch
      ToastMessageShow("Device not available",True)
   End Try
End Sub

Sub Serial1_Connected (Success As Boolean)
   If Success = True Then
      ToastMessageShow("Bluetooth connected to " & Serial1.Address, False)
        If ast.IsInitialized = False Then
        ast.Initialize(Me, "ast", Serial1.InputStream, Serial1.OutputStream)
        Tim.Enabled = False
    End If
      'timBT.Enabled = True
      Log("BT Connected")
    
    'Service.StopForeground(1) 'Return the service to the "background" (also removes the ongoing notification)
    If IsPaused(Main) Then
        Notification1.Sound = True
        Notification1.SetInfo("Bluetooth connected to " & Serial1.Address, "Done Successfully", Main)
        Notification1.AutoCancel = True
        Notification1.Notify(1)
        CallSub(Main,"UpdateUi")
    End If

   Else   'disconnected
      ToastMessageShow("Connection to " & Serial1.Address &" broken!", True)
          If IsPaused(Main) Then
        Notification1.Sound = True
        Notification1.SetInfo("Bluetooth Did Not Connect to " & Serial1.Address, " broken!", Main)
        Notification1.AutoCancel = True
        Notification1.Notify(1)
      
    End If
      btConnected = False
     Tim.Enabled = True
   End If
End Sub

Sub ast_Error
   Try
   ToastMessageShow("Connection is broken.", True)
         If IsPaused(Main) Then
        Notification1.Sound = True
        Notification1.SetInfo("Bluetooth Did Not Connect to " & Serial1.Address, " broken!", Main)
        Notification1.AutoCancel = True
        Notification1.Notify(1)
    End If
   If btConnected = False Then
     Tim.Enabled = True
    Else
   End If
    Catch
      ToastMessageShow("Device not available",True)
   End Try
End Sub

Sub ast_Terminated
Try
ToastMessageShow("Connection is broken.", True)
ast_Error
Catch
ToastMessageShow("Device not available",True)
End Try
End Sub

Sub ast_NewText(Text As String)
   Log("Text: " & Text)
   Log(Text.Length)
End Sub

Wondering what is wrong ?
 
Upvote 0

jahswant

Well-Known Member
Licensed User
Longtime User
yeah Sure : My timer was initialized to reconnect after 1 Secs so it was quite difficult for the app to do this within 1 Sec.So i Changed to 5 Secs now it will reconnect and have enough time to try to maintain the connection...
 
Upvote 0
Top