Android Question when my app goes to sleep... it disconnects from the network

vangogh

Active Member
Licensed User
Longtime User
maybe this is NOT a b4a issue, but maybe b4a can do something...

My app is a b4xpages app
It is connected with a prog on my pc using sockets using a LOCAL NETWORK (internal router)

I send a "PING" toi the server every 10 seconds. If I detect a network error, I reconnect
all works OK, if I keep the mobile "active"

as the times passes, this is what happens

the app is running OK (ping OK)
after a while the mobile screen becomes dark
if continues running (ping OK)
after a minute the mobile screen becomes "black" (?)
my app stops pinging
the connection drops

btw: b4abridge v 2.66 itself DISCONNECTS too... so I guess my devices closes the IP connection?

I can guess the IP socket is sleeping... as if I run the app in debug mode, it stops sendind logs to the IDE...
this is an exaple of logs. with the "network changes"
IP address OK: 192.168.1.54


Logger connected to: Xiaomi Mi 9 Lite
--------- beginning of system
--------- beginning of main

05/03 16:27:36 Sono BACK in rete ip: 192.168.1.54
05/03 16:27:36 Sono in rete ip:192.168.1.54
** Activity (main) Resume **

05/03 16:28:12 Sono in rete ip:192.168.1.54
05/03 16:28:13 Sono OUT rete ip:fe80::e805:9dff:fef4:e567%dummy0
05/03 16:28:13 Sono OUT rete ip:10.168.184.91

05/03 16:28:17 Sono BACK in rete ip: 192.168.1.54
05/03 16:28:18 Sono in rete ip:192.168.1.54

05/03 16:42:58 Sono OUT rete ip:fe80::e805:9dff:fef4:e567%dummy0
05/03 16:42:59 Sono OUT rete ip:10.168.184.91
05/03 16:43:03 Sono in rete ip:192.168.1.54

05/03 16:43:22 Sono OUT rete ip:fe80::e805:9dff:fef4:e567%dummy0
05/03 16:43:23 Sono OUT rete ip:10.168.184.91

05/03 16:43:27 Sono BACK in rete ip: 192.168.1.54
05/03 16:43:36 Sono in rete ip:192.168.1.54

...

... SO my mobile goes in and out from local network, making things very hard - my app need to remain connected

Can I force to stay in network, e.g. maintaining a "keep alive" - I don't know... disabiling battery optimization for my app?

add: If the mobile is connected to the power supply (not powered only by battery), the issue does NON happen. I am always connected.

Thank you
 
Last edited:
Solution
following, cut from https://developer.android.com/develop/background-work/services/fg-service-types


Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE

[Ricc] *HOW TO DO THAT?*
' now i do (copied from myLocation)
Service.StartForeground(nid, CreateNotification("..."))
Wait for the new version of B4A to come out. Currently stick with B4A's recommended target SDK of 33.

after doing all this, my app get disconnected (stops pinging the server) after 5 or 6 minutes
Make sure you're using target SDK of 33. Make sure the screen does not go off (newer versions of Android / device manufacturers kill WiFi with screen off)

OliverA

Expert
Licensed User
Longtime User
You can try @Erel's advice:
1. Make the service a foreground service.
2. Acquire a partial lock with PhoneWakeState.

Example: Background location tracking
Link: https://www.b4x.com/android/forum/threads/wifi-disconnected-when-screen-off.125693/post-785297

But in the end, it is also up to the manufacturer's implementation of Android that has an impact on this. Chinese manufacturers are very aggressive for battery maintenance reasons (throw Samsung into the mix).

I know that OnePlus will limit a partial lock to 299300 ticks (just under 5 minutes), which makes the use of such locks in programs that may require them for long durations useless. This limit seems to occur if other apps one the phone are also using wake locks. It looks like OnePlus limits the number of apps that can have long lasting wake locks (this is a pure guess. The 299300 ticks issue is based on an actual encounter with OnePlus's implementation of Android 14).
 
Upvote 0

vangogh

Active Member
Licensed User
Longtime User
ehm...I saw the "MyLocation" app

ehm... can I have a simpler help?

My app has a starter module, a main code module and a b4xpage

I am confused when I see the MyLocation app because i need to "extract" the code to have my app always in woke state

B4X:
'
'all I need is to add THIS code in a service mobule?
'
' Can I put it in  the starter service I already use for the Application_Error management?
'
' OR simply I can add a service module where to put only this code?
'
' (this code is EXTRACTED from the erel's MyLocation App)

Sub Process_Globals
    ''' Private nid As Int = 1 'not needed?
    Private lock As PhoneWakeState
End Sub

Sub Service_Create
    Service.AutomaticForegroundMode = Service.AUTOMATIC_FOREGROUND_NEVER 'we are handling it ourselves
    lock.PartialLock
End Sub

Sub Service_Start (StartingIntent As Intent)
    '''not needed?
    '''Service.StartForeground(nid, CreateNotification("..."))
End Sub

Sub Service_Destroy
    lock.ReleasePartialLock
End Sub


Is this code enough? can I use the STARTER service for all the code I need?


yes, yes, OK, "Ricc, you can try", but before doing a disaster, please let me call for an help...

Thank you!
Ricc
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
can I use the STARTER service for all the code I need?
No, use a separate service
'''not needed? '''Service.StartForeground(nid, CreateNotification("..."))
Yes, you will need this code to set the notification for the foreground service. Without setting the notification, Android will not see your service as a proper foreground service and kill the service.
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
i need to "extract" the code
Yes, you will need this code
You will also need to specify the service type in the manifest. The MyLocation example has

B4X:
SetServiceAttribute(Tracker, android:foregroundServiceType, "location")

in the manifest. You need to set the service type to the proper type depending on what your long-running service is trying to accomplish.

Link: https://developer.android.com/develop/background-work/services/fg-service-types
 
Upvote 0

vangogh

Active Member
Licensed User
Longtime User
No, use a separate service

Yes, you will need this code to set the notification for the foreground service. Without setting the notification, Android will not see your service as a proper foreground service and kill the service.

1) OK, I will simply add a service module with that code inside. Nothing to do in other modules, where I manage all the stuffs to do.

Right?

( I did it, it seems to work :p ! )



> you will need this code to set the notification for the foreground service. Without setting the notification, Android will not see your service as a proper foreground service and kill the service.

what should I do in my notificatiopn (as I need nothing)?

now I used the same code I copied from myLocation... not knowing what to do...
it seems to work (I don't know what it does but I don't bother ;-) šŸ˜ˆ

B4X:
'this is what the MyLocation does as a notification code

Sub CreateNotification (Body As String) As Notification
   
   'what should I do here? I kept this code....
   'bad bad bad programming philosophy, but it works

    Dim notification As Notification
    notification.Initialize2(notification.IMPORTANCE_LOW)
    notification.Icon = "icon"
    notification.SetInfo("Tracking location", Body, Main)
    Return notification

End Sub
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
now I used the same code I copied from myLocation... not knowing what to do...
it seems to work (I don't know what it does but I don't bother ;-) šŸ˜ˆ
It's just a sub to create a notification object that can be used to update the notification (such as the MyLocation does). In your case you want to change this
B4X:
notification.SetInfo("Tracking location", Body, Main)
line's first parameter to some other heading that is more appropriate for your application.
 
Upvote 0

vangogh

Active Member
Licensed User
Longtime User
You will also need to specify the service type in the manifest. The MyLocation example has

B4X:
SetServiceAttribute(Tracker, android:foregroundServiceType, "location")

in the manifest. You need to set the service type to the proper type depending on what your long-running service is trying to accomplish.

Link: https://developer.android.com/develop/background-work/services/fg-service-types

*pant* *pant* OK


addedd

B4X:
'IN MANIFEST

AddPermission(android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)

AddPermission(android.permission.FOREGROUND_SERVICE_CONNECTED_DEVICE)

AddPermission(android.permission.CHANGE_NETWORK_STATE)
AddPermission(android.permission.CHANGE_WIFI_STATE)
AddPermission(android.permission.CHANGE_WIFI_MULTICAST_STATE)
'
SetServiceAttribute(KeepAliveService, android:foregroundServiceType, "connectedDevice")
'(KeepAliveSeervice is the name of my service)


following, cut from https://developer.android.com/develop/background-work/services/fg-service-types


Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE

[Ricc] *HOW TO DO THAT?*
' now i do (copied from myLocation)
Service.StartForeground(nid, CreateNotification("..."))


Runtime prerequisites
At least one of the following conditions must be true:


then changed


B4X:
Sub CreateNotification (Body As String) As Notification
    'cut
    notification.SetInfo("Ping server", Body, Main)
    'cut
End Sub


added
Dim pws As PhoneWakeState pws.KeepAlive(True):
Dim pws As PhoneWakeState
pws.KeepAlive(True)
too

before doing all this, my app got disconnected after 1 minute

after doing all this, my app get disconnected (stops pinging the server) after 5 or 6 minutes

(As I can understand, it is still awake... but the wifi got disconnected)

I think that android disconnects from the wifi local network, so my app (still awake) goes disconnected...
as soon I connect a electrical power cord, the App restart pinging the server

something is still missing... i need to say to android not to disconnect from the WiFi, but I can't find that setting on my phone (so it is not standard)

and I did not do the part:
Constant to pass to startForeground() FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE
 
Last edited:
Upvote 0

OliverA

Expert
Licensed User
Longtime User
following, cut from https://developer.android.com/develop/background-work/services/fg-service-types


Constant to pass to startForeground()
FOREGROUND_SERVICE_TYPE_CONNECTED_DEVICE

[Ricc] *HOW TO DO THAT?*
' now i do (copied from myLocation)
Service.StartForeground(nid, CreateNotification("..."))
Wait for the new version of B4A to come out. Currently stick with B4A's recommended target SDK of 33.

after doing all this, my app get disconnected (stops pinging the server) after 5 or 6 minutes
Make sure you're using target SDK of 33. Make sure the screen does not go off (newer versions of Android / device manufacturers kill WiFi with screen off)
AddPermission(android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
This needs additional code to ensure that this setting is active and if not to request the user to turn battery optimizations of in the phone's settings.
 
Upvote 0
Solution
Top