Android Question Let app do things even if it's not launched

MFfromGermany

Member
Licensed User
Hey guys,

First of all: I apologize for opening a new thread, but somehow I couldn't find a thread matching my desires.

I'm kind of a rookie to this game (B4A), even though I've been programming in Visual Basic for years now.

And now my question: is there any possibility to let an app do actions (e.g. receive mails) without launching the app? I mean something like Outlook Mail app, which receives emails even if it's not launched.

Best regards from Germany
I'm very thankful for every hint or help :)
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
First of all: I apologize for opening a new thread, but somehow I couldn't find a thread matching my desires.
It is always better to start a new thread.

Outlook doesn't receive emails when it is not launched. It uses a service to periodically check for new mails.

Relevant tutorials:
Service Modules
Intent Filters - Intercepting SMS messages in the background
[URL='https://www.b4x.com/android/forum/threads/27065/#content']Creating a sticky service - long running background tasks
[/URL]
 
Upvote 0

MFfromGermany

Member
Licensed User
Well, now yesterday I found time to try out service modules. I tried everything: timer, StartServiceAt, Sticky Service, but it just wouldn't work.

I want my service to check for new mails every minute, then to download them, parse them and save them to a database-table. The code itself works pretty fine. But I just don't get my service to work every minute. It just works once after I closed my app and then seems either to stop or not to start again. Maybe you can help me with that.

Here's my code:

B4X:
#Region  Service Attributes
    #StartAtBoot: True
    #StartCommandReturnValue: android.app.Service.START_STICKY
#End Region

Sub Process_Globals
    'KONNEKTIVITÄTSVARIABLEN
    Dim ConnectionString As String
    Dim Zugangscode As String
    Dim ConnectionStringDisponent As String
   
    'DATENBANKVARIABLEN
    Dim Auftragsarchiv As SQL
   
    'EMAILVARIABLEN
    Dim POP As POP3
    Dim SMTP As SMTP
    Dim ANR As String
    Dim ÄnderungsBoolean As Boolean
   
    'BENACHRICHTIGUNG
    Dim N As Notification
    Dim MP As MediaPlayer
    Dim PV As PhoneVibrate
End Sub

Sub Service_Create
    'Datenbank
    Auftragsarchiv.Initialize(File.DirInternal, "Auftragsarchiv.db", True)
    If File.Exists(File.DirInternal, "ArchiveCreated.txt") = False Then
        File.WriteString(File.DirInternal, "ArchiveCreated.txt", "Archive.db has been created.")   
        Auftragsarchiv.ExecNonQuery("CREATE TABLE Aufträge (Auftragsnummer TEXT, Adresse TEXT, Details TEXT, Status TEXT)")
    End If
       
    'Konnektivitätseinstellungen
    Dim TR As TextReader
    If File.Exists(File.DirInternal, "ConnectionString.txt") = True Then
        TR.Initialize(File.OpenInput(File.DirInternal, "ConnectionString.txt"))
        ConnectionString = TR.ReadLine
        TR.Close
    End If
    If File.Exists(File.DirInternal, "Zugangscode.txt") = True Then
        TR.Initialize(File.OpenInput(File.DirInternal, "Zugangscode.txt"))
        Zugangscode = TR.ReadLine
        TR.Close
    End If
    If File.Exists(File.DirInternal, "ConnectionStringDisponent.txt") = True Then
        TR.Initialize(File.OpenInput(File.DirInternal, "ConnectionStringDisponent.txt"))
        ConnectionStringDisponent = TR.ReadLine
        TR.Close
    End If
       
    'Email - nur, wenn Konnektivitätseinstellungen vorgenommen wurden.
    If File.Exists(File.DirInternal, "RanFirstTime.txt") = True Then
        SMTP.Initialize("smtp.gmail.com", 587, ConnectionString, Zugangscode, "SMTP")
        SMTP.StartTLSMode = True
        POP.Initialize("pop.gmail.com", 995, ConnectionString, Zugangscode, "pop")
           POP.UseSSL = True
    End If
   
    'Benachrichtigungston
    MP.Initialize
    MP.Load(File.DirAssets, "q96-schleife1.wav")
   
   
End Sub

Sub Service_Start (StartingIntent As Intent)
    StartServiceAt(Null, TimeToNextMinute, True) 'Service will restart every minute
    CallSub(Null, CheckForMails)
End Sub

Sub Service_Destroy
   
End Sub

Sub POP_ListCompleted (Success As Boolean, Messages As Map)
    If Success = False Then
       
    Else
        For i = 0 To Messages.Size - 1
            POP.DownloadMessage(Messages.GetKeyAt(i), True)
        Next       
    End If
    POP.Close
End Sub

Sub POP_DownloadCompleted (Success As Boolean, MessageId As Int, MessageText As String)
    If Success = False Then
        Log(LastException.Message)
        POP.ListMessages
    Else
        Dim m As Message
        m = MailParser.ParseMail(MessageText, File.DirRootExternal)
        If m.FromField.Contains(ConnectionStringDisponent) = True Then
            ANR = m.Subject.Replace(" ", "")
            Dim ListOfMaps As List
            ListOfMaps.Initialize
            Dim Map As Map
            Map.Initialize
            Map.Put("Auftragsnummer", ANR)
            Map.Put("Details", m.Body)
            Map.Put("Status", "erhalten")
            ListOfMaps.Add(Map)
            Dim Cursor As Cursor
            Cursor = Auftragsarchiv.ExecQuery("SELECT Auftragsnummer FROM Aufträge WHERE Auftragsnummer LIKE " & "'" & ANR & "%'")
            If Cursor.RowCount = 0 Then
                DBUtils.InsertMaps(Auftragsarchiv, "Aufträge", ListOfMaps)
                SMTP_erhalten
                ÄnderungsBoolean = False
                N.Initialize
                N.Icon = "icon"
                N.SetInfo2("Neuer Einsatzauftrag", "Auftragsnummer: " & ANR, ANR, Main)
                N.Sound = False
                N.Vibrate = False
                N.AutoCancel = True
                N.Notify(1)
                MP.Play
                PV.Vibrate(1500)
            Else
                Dim WhereFields As Map
                WhereFields.Initialize
                WhereFields.Put("Auftragsnummer", ANR)
                DBUtils.UpdateRecord(Auftragsarchiv, "Aufträge", "Details", m.Body, WhereFields)
                SMTP_Anderungerhalten
                ÄnderungsBoolean = True
                N.Initialize
                N.Icon = "icon"
                N.SetInfo2("Änderung von Einsatzdaten", "Auftragsnummer: " & ANR, ANR, Main)
                N.Sound = False
                N.Vibrate = False
                N.AutoCancel = True
                N.Notify(1)
                MP.Play
                PV.Vibrate(1500)
            End If
        End If
    End If
   
End Sub

Sub SMTP_erhalten
    SMTP.To.Add(ConnectionStringDisponent)
    SMTP.Subject = ANR
    SMTP.Body = "erhalten"
    SMTP.Send
End Sub

Sub SMTP_Anderungerhalten
    SMTP.To.Add(ConnectionStringDisponent)
    SMTP.Subject = ANR
    SMTP.Body = "Änderung erhalten"
    SMTP.Send
End Sub

Sub SMTP_MessageSent(Success As Boolean)
      Log(Success)
      If Success = False Then
        Log(LastException.Message)
        If ÄnderungsBoolean = False Then
            SMTP_erhalten
        Else
            SMTP_Anderungerhalten
        End If
     End If
End Sub

Sub CheckForMails
    'SERVICE WIRD NUR GESTARTET, WENN DIE KONNEKTIVITÄTSEINSTELLUNGEN BEREITS VORGENOMMEN WURDEN.
    If File.Exists(File.DirInternal, "RanFirstTime.txt") = True Then
        POP.ListMessages
    End If
End Sub

Sub TimeToNextMinute As Long
    Dim NextMin As Long
        NextMin = DateTime.Now + DateTime.TicksPerMinute
        NextMin = NextMin - (NextMin Mod DateTime.TicksPerMinute)
    Return NextMin
End Sub
 
Upvote 0

MFfromGermany

Member
Licensed User
I figured it out myself: the problem was that I called "POP.Close" in POP_ListCompleted, so I had to Call "POP.Initialize" in CheckForMails again and then it worked fine. Meanwhile I decided to use "Service.StartForeground" in order to keep the process working - it just fits better to what I need the service for - and also changed some other things. If you're interested in how my code looks right now then I can post it again.

But thank you very much for your quick help.
 
Upvote 0

awakenblueheart

Member
Licensed User
Longtime User
Checking email automatically for every 1~2 minutes maybe. Make a pop up message. Besides, I wanna get notification for all my email.
If possible, can pop up the inbox email with specific sender.

Thanks!
 
Upvote 0

MFfromGermany

Member
Licensed User
Pease note that I did not forget you, I'm just very busy at the moment. I'll create a short tutorial for you as soon as I find some space to do so.
 
Upvote 0
Top