Android Question httpjob needs 100 sec for first result

olivere

Member
Licensed User
Longtime User
Hello,

I encounter a strange problem: httpjob (okHttpUtils2 lib) takes nearly 100 secs to complete the first task. All subsequent requests are performed in normal time( 0.5-2 seconds). Tested on several phones with Android 14 (Samsung A25, Samsung Galaxy A04)

Some time before, a similar problem has already been reported (see link above), but the solution there provided by Erel does not help in this current case:
https://www.b4x.com/android/forum/t...-at-a-random-time-depending-on-devices.149846

Attached, I modified the sample project from the above thread.
ProblemHTTP:
Private Sub Button1_Click
  
Dim fTicksIni As Long = DateTime.Now
    Dim fTicksEnd As Long
    Dim fTicksEnd As Long
    Dim j As HttpJob
    j.Initialize("", Me)
    j.Download("https://www.b4x.com")
    Log("Starting Download")
    Label1.Text = "Waiting..."
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Label1.Text = j.GetString
        fTicksEnd= DateTime.Now
        Log( "Completed after "&NumberFormat((((((fTicksEnd-fTicksIni)/DateTime.TicksPerSecond)))),1,4) &" seconds"  )
    End If
    j.Release
    End Sub

Here is the log file:
Log:
Logger connected to:  samsung SM-A256B
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
StartHttpUtils2Service
*** Receiver (httputils2service) Receive (first time) ***
*** mainpage: B4XPage_Created
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
Starting Download
Completed after 90.84 seconds
** Activity (main) Pause event (activity is not paused). **
*** mainpage: B4XPage_Disappear [mainpage]

With such a behaviour, the lib is hardly usable anymore.
It would be great if anybody could point me to the right direction if I'm doing something wrong and/or have a fast solution for this problem,.
tx
Oliver

Edit: Same behavour also with BETA 13!
 

Attachments

  • ProblemHTTP.zip
    12.1 KB · Views: 46
Last edited:

zed

Active Member
Licensed User
No problems compiling

Log result
Log:
Logger connecté à :  Xiaomi M2101K7AG
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
*** mainpage: B4XPage_Created
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
*** Receiver (httputils2service) Receive (first time) ***
<!DOCTYPE html><html lang="en-US"><head itemscope itemtype="https://schema.org/WebSite"><meta charset="UTF-8" /><meta name="description" content="B4X is a programming language and a set of cross-platform RAD development tools that allow complete beginners, citizen developers, and professionals to build real-world Android, iOS and desktop solutions" /><meta name="keywords" content="development, programming, basic, ios, android, iot" /><meta name="viewport" content="width=device-width, initial-scale=1" /><link media="all" href="https://www.b4x.com/wp/wp-content/cache/autoptimize/css/autoptimize_cc4308c5dffbaf9a36b7a4228cfc1a71.css" rel="stylesheet" /><title>Cross platform RAD development tools | B4X</title> <script type="application/ld+json">{
  "@context": "http://schema.org",
  "@type": "WebSite",
  "url": "https://www.b4x.com/",
  "potentialAction": {
    "@type": "SearchAction",
    "target": "https://www.b4x.com/android/forum/pages/results/?query={search_term_string}",
    "query-input": "required name=search_term_string"
  }
}</script><link rel="dns-prefetch" href="//fonts.googleapis.com" /><link rel="dns-prefetch" href="//s.w.org" /><link rel="alternate" type="application/rss+xml" title="B4X &raquo; Feed" href="https://www.b4x.com/feed/" /><link rel="alternate" type="application/rss+xml" title="B4X &raquo; Comments Feed" href="https://www.b4x.com/comments/feed/" /><link rel="canonical" href="https://www.b4x.com/" /> <script>window._wpemojiSettings = {"baseUrl":"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/72x72\/","ext":".png","svgUrl":"https:\/\/s.w.org\/images\/core\/emoji\/12.0.0-1\/svg\/","svgExt":".svg","source":{"concatemoji":"https:\/\/www.b4x.com\/wp\/wp-includes\/js\/wp-emoji-release.min.js?ver=5.3.2"}};
            !function(e,a,t){var r,n,o,i,p=a.createElement("canvas"),s=p.getContext&&p.getContext("2d");function c(e,t){var a=String.fromCharCode;s.clearRect(0,0,p.width,p.height),s.fillText(a.apply(this,e),0,0);var r=p.toDataURL();return s.clearRect(0,0,p.width,p.height),s.fillText(a.apply(this,t),0,0),r===p.toDataURL()}function l(e){if(!s||!s.fillText)return!1;switch(s.textBaseline="top",s.font="600 32px Arial",e){case"flag":return!c([127987,65039,8205,9895,65039],[127987,65039,8203,9895,65039])&&(!c([55356,56826,55356,56819],[55356,56826,8203,55356,56819])&&!c([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]));case"emoji":return!c([55357,56424,55356,57342,8205,55358,56605,8205,55357,56424,55356,57340],[55357,56424,55356,57342,8203,55358,56605,8203,55357,56424,55356,57340])}return!1}function d(e){var t=a.createElement("script");t.src=e,t.defer=t.type="text/javascript",a.getElementsByTagName("head")[0].appendChild(t)}for(i=Array("flag","emoji"),t.supports={everything:!0,everythingExceptFlag:!0},o=0;o<i.length;o++)t.supports[i[o]]=l(i[o]),t.supports.everything=t.supports.everything&&t.supports[i[o]],"flag"!==i[o]&&(t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&t.supports[i[o]]);t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&!t.supports.flag,t.DOMReady=!1,t.readyCallback=function(){t.DOMReady=!0},t.supports.everything||(n=function(){t.readyCallback()},a.addEventListener?(a.addEventListener("DOMContentLoaded",n,!1),e.addEventListener("load",n,!1)):(e.attachEvent("onload",n),a.attachEvent("onreadystatechange",function(){"complete"===a.readyState&&t.readyCallback()})),(r=t.source||{}).concatemoji?d(r.concatemoji):r.wpemoji&&r.twemoji&&(d(r.twemoji),d(r.wpemoji)))}(window,document,window._wpemojiSettings);</script> <link rel="stylesheet" id="dashicons-css" href="https://www.b4x.com/wp/wp-includes/css/dashicons.min.css?ver=5.3.2" media="all" /><link rel="stylesheet" id="altitude-google-fonts-css" href="https://fonts.googleapis.com/css?family=Ek+Mukta%3A200%2C800&#038;ver=1.3.1" media="all" /> <script src="https://www.b4x.com/wp/wp-includes/js/jquery/jquery.js?ver=1.12.4-wp"></script> <script>var vlpp_vars = {"prettyPhoto_rel":"wp-video-lightbox","animation_speed":"fast","slideshow":"5000","autoplay_slideshow":"false","opacity":"0.80","show_title":"true","allow_resize":"true","allow_expand":"true","default_width":"640","default_height":"480","counter_separator_label":"\/","theme":"pp_default","horizontal_padding":"20","hideflash":"false","wmode":"opaque","autoplay":"true","modal":"false","deeplinking":"false","overlay_gallery":"true","overlay_gallery_max":"30","keyboard_shortcuts":"true","ie6_fallback":"false"};</script> <link rel="https://api.w.org/" href="https://www.b4x.com/wp-json/" /><link rel="EditURI" type="application/rsd+xml" title="RSD" href="https://www.b4x.com/wp/xmlrpc.php?rsd" /><link rel="alternate" type="application/json+oembed" href="https://www.b4x.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.b4x.com%2F" /><link rel="alternate" type="text/xml+oembed" href="https://www.b4x.com/wp-json/oembed/1.0/embed?url=https%3A%2F%2Fwww.b4x.com%2F&#038;format=xml" /> <script>WP_VIDEO_LIGHTBOX_VERSION="1.8.9";
            WP_VID_LIGHTBOX_URL="https://www.b4x.com/wp/wp-content/plugins/wp-video-lightbox";
                        function wpvl_paramReplace(name, string, value) {
                // Find the param with regex
                // Grab the first character in the returned string (should be ? or &)
                // Replace our href string with our new value, passing on the name and delimeter
                var re = new RegExp("[\?&]" + name + "=([^&#]*)");
                var matches = re.exec(string);
                var newString;
                if (matches === null) {
                    // if there are no params, append the parameter
                    newString = string + '?' + name + '=' + value;
                } else {
                    var delimeter = matches[0].charAt(0);
                    newString = string.replace(re, delimeter + name + "=" + value);
                }
                return newString;
            }</script><link rel="icon" href="https://www.b4x.com/wp/wp-content/themes/altitude-pro/images/favicon.ico" /><link rel="pingback" href="https://www.b4x.com/wp/xmlrpc.php" /><meta itemprop="name" content="B4X" /><meta itemprop="url" content="https://www.b4x.com/" /><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png?v=m2lLkKq9bl"><link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png?v=m2lLkKq9bl"><link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png?v=m2lLkKq9bl"><link rel="manifest" href="/manifest.json?v=m2lLkKq9bl"><link rel="mask-icon" href="/safari-pinned-tab.svg?v=m2lLkKq9bl" color="#5bbad5"><link rel="shortcut icon" href="/favicon.ico?v=m2lLkKq9bl"><meta name="theme-color" content="#ffffff"><link href="https://fonts.googleapis.com/css?family=Open+Sans:300,400" rel="stylesheet"> <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-MZNZG44');</script>
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-1987329-1"></script> <script>window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'UA-1987329-1', { 'anonymize_ip': true });</script> <style type="text/css">.site-title a { background: url(https://www.b4x.com/wp/wp-content/uploads/2016/07/Logo_white.png) no-repeat !important; }</style></head><body class="home page-template-default page page-id-268 wp-embed-responsive custom-header header-image header-full-width full-width-content genesis-breadcrumbs-hidden genesis-footer-widgets-visible front-page featured-section" itemscope itemtype="https://schema.org/WebPage"><div class="site-container"><ul class="genesis-skip-link"><li><a href="#genesis-content" class="screen-reader-shortcut"> Skip to main content</a></li><li><a href="#genesis-footer-widgets" class="screen-reader-shortcut"> Skip to footer</a></li></ul><header class="site-header" itemscope itemtype="https://schema.org/WPHeader"><div class="wrap"><div class="title-area"><h1 class="site-title" itemprop="headline"><a href="https://www.b4x.com/">B4X</a></h1><p class="site-description" itemprop="description">Develop Android, iOS and IoT applications</p></div><nav class="nav-primary" aria-label="Main" itemscope itemtype="https://schema.org/SiteNavigationElement" id="genesis-nav-primary"><div class="wrap"><ul id="menu-headermenu" class="menu genesis-nav-menu menu-primary js-superfish"><li id="menu-item-17" class="menu-item menu-item-type-custom menu-item-object-custom current-menu-item current_page_item menu-item-17"><a href="/" aria-current="page" itemprop="url"><span itemprop="name">Home</span></a></li><li id="menu-item-69" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-69"><a itemprop="url"><span itemprop="name">Products</span></a><ul class="sub-menu"><li id="menu-item-70" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-70"><a href="https://www.b4x.com/b4a.html" itemprop="url"><span itemprop="name">B4A (Android)</span></a></li><li id="menu-item-102" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-102"><a href="https://www.b4x.com/b4i.html" itemprop="url"><span itemprop="name">B4i (iOS)</span></a></li><li id="menu-item-101" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-101"><a href="https://www.b4x.com/b4j.html" itemprop="url"><span itemprop="name">B4J (Desktop)</span></a></li><li id="menu-item-71" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-71"><a href="https://www.b4x.com/b4r.html" itemprop="url"><span itemprop="name">B4R (Arduino)</span></a></li></ul></li><li id="menu-item-75" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-75"><a href="https://www.b4x.com/showcase.html" itemprop="url"><span itemprop="name">Showcase</span></a></li><li id="menu-item-86" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-86"><a href="https://www.b4x.com/store.html" itemprop="url"><span itemprop="name">Store</span></a></li><li id="menu-item-462" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-has-children menu-item-462"><a itemprop="url"><span itemprop="name">Learn</span></a><ul class="sub-menu"><li id="menu-item-461" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-461"><a href="https://www.b4x.com/learn.html" itemprop="url"><span itemprop="name">General</span></a></li><li id="menu-item-459" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-459"><a href="https://www.b4x.com/android/documentation.html" itemprop="url"><span itemprop="name">Guides</span></a></li><li id="menu-item-458" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-458"><a href="https://www.b4x.com/etp.html" itemprop="url"><span itemprop="name">Video Tutorials</span></a></li><li id="menu-item-460" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-460"><a href="https://www.b4x.com/glossary/" itemprop="url"><span itemprop="name">Glossary</span></a></li></ul></li><li id="menu-item-298" class="menu-item menu-item-type-post_type menu-it
Message longer than Log limit (4000). Message was truncated.
0.946 s  (Count: 0)
 
Upvote 0

olivere

Member
Licensed User
Longtime User
I'm unable to reproduce it. Are you using B4A v12.8+ ?
Yes, the problem occurs both with B4A 12.8 and 13 BETA; both with older java version (11.0.1) and newest (19.0.2)

To check, whether the httpjob object is initialized, I enhanced the code a little bit:
B4X:
Private Sub Button1_Click
    Dim fTicksIni As Long = DateTime.Now
    Dim fTicksEnd As Long
    Dim fTicksEnd As Long
    Dim j As HttpJob
    j.Initialize("", Me)
    Log("Starting Init")
    Do While j.IsInitialized =False
    Sleep(1000)
    Loop
    fTicksEnd= DateTime.Now
    Log( "Completed after "&NumberFormat((((((fTicksEnd-fTicksIni)/DateTime.TicksPerSecond)))),1,4) &" seconds"  )
   
    Log("Starting Download")
    fTicksIni  = DateTime.Now
    j.Download("https://www.b4x.com")
    Label1.Text = "Waiting..."
    Wait For (j) JobDone(j As HttpJob)
    If j.Success Then
        Label1.Text = j.GetString
        fTicksEnd= DateTime.Now
        Log( "Completed after "&NumberFormat((((((fTicksEnd-fTicksIni)/DateTime.TicksPerSecond)))),1,4) &" seconds"  )
    End If
    j.Release
End Sub

But the result is the same: initialization is done, but the first request takes an eternity.. All subsequent requests are ok..

B4X:
Logger connected to:  samsung SM-A256B
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
StartHttpUtils2Service
*** Receiver (httputils2service) Receive (first time) ***
*** mainpage: B4XPage_Created
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
Starting Init
Completed after 0 seconds
Starting Download
Completed after 90.9 seconds
Starting Init
Completed after 0.001 seconds
Starting Download
Completed after 0.536 seconds
Starting Init
Completed after 0.001 seconds
Starting Download
Completed after 0.311 seconds
 
Upvote 0

olivere

Member
Licensed User
Longtime User
I'm unable to reproduce it. Are you using B4A v12.8+ ?
On the Samsung A04 (Android 14), the following error occurs:

B4X:
Logger connected to:  samsung SM-A047F
--------- beginning of main
Copying updated assets files (1)
*** Service (starter) Create ***
** Service (starter) Start **
** Activity (main) Create (first time) **
StartHttpUtils2Service
*** Receiver (httputils2service) Receive (first time) ***
*** mainpage: B4XPage_Created
*** mainpage: B4XPage_Appear
** Activity (main) Resume **
** Service (starter) Start **
Starting Init
Completed after 0.001 seconds
Starting Download
** Activity (main) Pause event (activity is not paused). **
** Service (starter) Destroy (ignored)**
java.lang.RuntimeException: Unable to create service b4a.example.starter: java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:5111)
    at android.app.ActivityThread.-$$Nest$mhandleCreateService(Unknown Source:0)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2506)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loopOnce(Looper.java:230)
    at android.os.Looper.loop(Looper.java:319)
    at android.app.ActivityThread.main(ActivityThread.java:8893)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:608)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
    at anywheresoftware.b4a.shell.Shell.virtualAssets(Shell.java:164)
    at anywheresoftware.b4a.shell.Shell.start(Shell.java:102)
    at anywheresoftware.b4a.ShellBA.raiseEvent2(ShellBA.java:105)
    at b4a.example.starter.onCreate(starter.java:34)
    at android.app.ActivityThread.handleCreateService(ActivityThread.java:5098)
    ... 9 more
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
    at anywheresoftware.b4a.shell.ShellConnector.sendControlMessage(ShellConnector.java:61)
    at anywheresoftware.b4a.shell.Shell.virtualAssets(Shell.java:124)
    ... 13 more

All my test devices have Samsung Knox preinstalled - maybe this might be a reason ?
 
Upvote 0

olivere

Member
Licensed User
Longtime User
What network are you using?, try to change ISP to do that.
Thank you for this hint: if I disable WiFi and use regular mobile data to go into internet, everything works well.

@Erel: so the problem seem to be caused by the Wifi connectivity. Do you have a solution how to solve it, for many user prefer using Wifi networks to save mobile data costs.
 
Last edited:
Upvote 0

teddybear

Well-Known Member
Licensed User
It is not related to WiFi, the issue is from your ISP, you need to contact your ISP for the solution.
To many users, is the wifi they use from same ISP? not all wifi networks of ISP behave like that. I think Erel's testing also uses WiFi.
 
Last edited:
Upvote 0

olivere

Member
Licensed User
Longtime User
It is not related to WiFi, the issue is from your ISP, you need to contact your ISP for the solution.
To many users, is the wifi they use from same ISP? not all wifi networks of ISP behave like that. I think Erel's testing also uses WiFi.
I'm very sure that the problem has nothing to do with the ISP. Other apps and common internet functionality on the phone are working well with WiFi, the problem only occurs with B4A and httpjob in newer versions. Apps built with former versions of okhttputils2 (before changing to receiver mode) are also working well.
 
Upvote 0

Daestrum

Expert
Licensed User
Longtime User
Could you not try it with Knox turned off?
 
Upvote 0

TILogistic

Expert
Licensed User
Longtime User
It could be due to the remote server request cache, I have experienced the difference in response time compared to the first request.

ex.
1724699949677.png
 
Last edited:
Upvote 0

olivere

Member
Licensed User
Longtime User
It is not related to WiFi, the issue is from your ISP, you need to contact your ISP for the solution.
To many users, is the wifi they use from same ISP? not all wifi networks of ISP behave like that. I think Erel's testing also uses WiFi.
In meantime, I tried some different other wifi networks - and using other wifi, it works. One of the working wifi has the same ISP as the wifi showing the problem, so I think this should be a confirmation that the reason is not located in the ISP.

It could be due to the remote server request cache, I have experienced the difference in response time compared to the first request.
Generally yes, but not in this case: both the delay time is much too long and the problem also occurs when changing the url to other servers

Could you not try it with Knox turned off?
In meantime I also tried this, but not effect
 
Upvote 0

Spavlyuk

Active Member
Licensed User
I've used the following code in one of my apps where I had a similar issue, maybe it will work for you.

B4X:
StartReceiver(HttpUtils2Service)
Do While HttpUtils2Service.TempFolder = ""
    Sleep(100)
    Log("Waiting for HttpUtils2Service...")
Loop
 
Upvote 0

olivere

Member
Licensed User
Longtime User
It doesn't look like a problem in OkHttp or OkHttpUtils2.

It is a problem with your wifi.
Tx Erel, but what do you suggest ?
In most cases, users do not have any possibilities to change/examine wifi configuration, for they have no access to router settings.
Also, the problem only exists with (newer) B4A apps, other apps are working well in the same wifi..
 
Upvote 0

olivere

Member
Licensed User
Longtime User
I've used the following code in one of my apps where I had a similar issue, maybe it will work for you.

B4X:
StartReceiver(HttpUtils2Service)
Do While HttpUtils2Service.TempFolder = ""
    Sleep(100)
    Log("Waiting for HttpUtils2Service...")
Loop
TX, but this also does not help
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Tx Erel, but what do you suggest ?
In most cases, users do not have any possibilities to change/examine wifi configuration, for they have no access to router settings.
Also, the problem only exists with (newer) B4A apps, other apps are working well in the same wifi..
It looks like a problem not related to B4A.
We are all using OkHttpUtil2 with wifi connections, all day long, with no issues.
 
Upvote 0

teddybear

Well-Known Member
Licensed User
You can do a simple test . deploy a webserver for that on LAN , and then run the app to see what happens.
For apps of client and server, they don't care whether data communication is via LAN or WAN
 
Upvote 0
Top