Android Question Starting at boot up or on demand using a Receiver

John Naylor

Active Member
Licensed User
Longtime User
Attached my test app.

I am using two receivers. The main one called MyReceiver is set up to run itself once a minute and display a notification with a counter.


B4X:
Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)

    'Do whatever you need to do.
    'StartActivity (Main) for example
    'I'm just going to display a notification
            
    Dim n As Notification
    n.Initialize
    n.Icon = "icon"
    n.SetInfo("Test", "Receiver fired - " & cnt, Main)
    n.Notify (1)
    cnt = cnt + 1
    
    
    Dim t As Long = DateTime.Now + 1000 * 60        'Set the next time the receiver is fired to time + 1 minute
    StartReceiverAt (Me, t, True)
        
End Sub

The other receiver (StartupReceiver) relies on a manifest entry


B4X:
AddPermission(android.permission.RECEIVE_BOOT_COMPLETED)
AddReceiverText(StartupReceiver, <intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>)

which allows me to see when my device has booted up completely. It then sets up my original MyReceiver to be called in about a minute.


B4X:
Private Sub Receiver_Receive (FirstTime As Boolean, StartingIntent As Intent)

    'Check the manifest - you will see
    '
    'AddPermission(android.permission.RECEIVE_BOOT_COMPLETED)
    'AddReceiverText(StartupReceiver, <intent-filter>
    '<action android:name="android.intent.action.BOOT_COMPLETED"/>
    '</intent-filter>)
    '
    'Note the name 'StartupReceiver' - the same name as this receiver.

    'Do whatever you need to set your app up for the future. Here I'm just setting it up to fire the 'MyReceiver' code in about a minute
    'As the device is just booting up, it may well be longer than a minute. potentially quite a bit longer depending on what else is starting.
    'Be patient, if a receiver wasn't fired on time it'll be fired as soon as possible.
    
    Dim t As Long = DateTime.Now + 1000 * 60        'Fire the next receiver in one minute from now
    StartReceiverAt (MyReceiver, t, True)
End Sub

Anything missing? Is this how it's supposed to be done?

TIA
 

Attachments

  • ReceiverTest.zip
    12 KB · Views: 65

John Naylor

Active Member
Licensed User
Longtime User
Does it work?

An interval of 1 minute can be problematic.
It appears to yes. 1 minute interval is indeed problematic and fails randomly after 20 minutes to an hour but that issue goes away with a longer interval.

Nothing else I need to add for best practice?
 
Upvote 0
Top