Spanish Leer list en segundo plano

piramide

Member
Licensed User
Longtime User
Buenos días.. tengo una pequeña app donde muestro un list con numeros de telefono y lo que necesito es que cada cierto tiempo (un intervalo de 5 segundos por ejemplo) se vayan leyendo cada uno de los registros del list y hacer algo (enviar un mensaje, sms o whatsapp).
Con la app en primer plano logro que funcione pero cuando la app queda en segundo plano deja de funcionar..

Es claro que algo estoy haciendo mal, me gustaria saber si alguien trabajo en algun proyecto similar .. y que me de una mano por favor..

tengo un modulo servicio:

.
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.
    Dim cuenta As Int
    cuenta = 0
    Dim hora As String
    Dim current_min As String
    Dim N As Notification
    Dim timer1 As Timer
    Dim cont As Int
End Sub

Sub Service_Create
    'Entra la 1era vez que inicia el servicio
    'Aqui se pueden inicializar los procesos y las variables globales
    'Este se mantiene en marcha hasta que se llame a StopService o se destruya
    'Establecimiento de las Propiedades de Notificación

    hora = DateTime.Time(DateTime.Now)
    
    
    timer1.Initialize("tim",3000)
    timer1.Enabled = True
    cont = 0
    
End Sub


Sub tim_tick
    cont = cont +1
    ToastMessageShow(cont,False)
    CallSub(Main, "muestra")
End Sub


Sub Service_Start (StartingIntent As Intent)

End Sub

Sub Service_Destroy

End Sub



y en el main :


B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim tmrSplashFade As Timer
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.

    Private lblDesc As Label
    Private btnAccessibility As Button
    Private CheckBox1 As CheckBox
    Private btnAction As Button
    Private txtMsg As EditText
    Private btnSend As Button
    Private xui As XUI
    Private clv1 As CustomListView
    Private Label1 As B4XView
    Type CardData (Nombre As String, Telefono As String)
    Private Button1 As Button
    
    Dim registro As CardData
    
    Dim lista As List
    
    Private ImageView1 As B4XView
    Dim Timer1 As Timer
    Private IdLista As Int
    
    Dim intFadeCount As Int
    
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    
    If FirstTime Then
        Activity.LoadLayout("Splash")
        tmrSplashFade.Initialize("tmrSplash", 50)
        tmrSplashFade.Enabled = True
        intFadeCount = 0
    End If
    
    Activity.AddMenuItem("Salir","Salir")
    Activity.AddMenuItem("Configuracion","Configuracion")
    
End Sub


Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub btnSend_Click
    
    btnSend.Enabled = False
    
    StartService(Servicio)
    
    
End Sub

Sub Salir_Click
    CancelScheduledService(Servicio)  ' Para el  StartServiceAt
    StopService(Servicio)
    ExitApplication
End Sub


Public Sub muestra
    ' Utilizo la variable cont creada en el Servicio
    IdLista = Servicio.cont
    If IdLista <  lista.Size Then
        registro = lista.Get(IdLista)  'lista.Get(i)
        Log(registro.Telefono&" - "&registro.Nombre)
    Else
        btnSend.Enabled = True
        CancelScheduledService(Servicio)  ' Para el  StartServiceAt
        StopService(Servicio)
    End If
End Sub


Nota: el contador del servicio sigue funcionando con la app en segundo plano pero no tiene acceso al Sub muestra del Main
Desde ya, gracias !!!
 

josejad

Expert
Licensed User
Longtime User
Hola pirámide:

Echando sólo un vistazo rápido al hilo y sin ser demasiado bueno con los servicios, veo dos cosas:
- Creo que para una tarea cada 5 segundos el S.O. detectará demasiado uso y terminará cerrando la app. Usa intervalos más largos (minutos).
- Para llamar a la sub de main, creo que deberías usar CallSubDelayed, ya que, aunque el servicio siga corriendo, la Activity puede ser cerrada por el sistema operativo y por tanto no estar ya disponible.

Consejos:
- Cambia a B4XPages, te ahorrarás transtornos con el ciclo de vida de Android, ya que no se cerrará la activity.
- Echa un ojo al ejemplo de Erel para mantener un servicio en segundo plano, y modifícalo con tu servicio.

saludos,
 

piramide

Member
Licensed User
Longtime User
Hola a todos.. gracias por responder Jose Aguilar.. estuve viendo lo que me comentas pero aun no he podido resolver ni hacer que la app funcione como quiero.. voy a seguir estudiando el caso y comentare lo sucedido..
 
Top