Android Question websocket android.os.NetworkOnMainThreadException

fransvlaarhoven

Active Member
Licensed User
Longtime User
Hello,

I've created a "push connection" between a B4A-client and a B4J-server based on the information found in "Custom WebSocket Based Push Framework".

All seems to work fine but I see a problem when the application n the server stops running.

Then the Anroid-client generates the error:

android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1450)
at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:319)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.shutdownAndFreeSslNative(ConscryptFileDescriptorSocket.java:966)
at com.android.org.conscrypt.ConscryptFileDescriptorSocket.close(ConscryptFileDescriptorSocket.java:961)
at io.crossbar.autobahn.websocket.WebSocketConnection.failConnection(WebSocketConnection.java:211)
at io.crossbar.autobahn.websocket.WebSocketConnection.access$16(WebSocketConnection.java:202)
at io.crossbar.autobahn.websocket.WebSocketConnection$2.handleMessage(WebSocketConnection.java:530)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6497)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ExecInit.main(ExecInit.java:49)
at com.android.internal.os.RuntimeInit.nativeFinishInit(Native Method)
at com.android.internal.os.RuntimeInit.main(RuntimeInit.java:285)

I'm running Android version .1.0 on a Nexus Phone wit Copperhaed OS on it.

I can avoid the error using the code

Dim jo As JavaObject
jo.InitializeStatic("android.os.Build.VERSION")
If jo.GetField("SDK_INT") > 9 Then
Dim policy As JavaObject
policy = policy.InitializeNewInstance("android.os.StrictMode.ThreadPolicy.Builder", Null)
policy = policy.RunMethodJO("permitAll", Null).RunMethodJO("build", Null)
Dim sm As JavaObject
sm.InitializeStatic("android.os.StrictMode").RunMethod("setThreadPolicy", Array(policy))
End If

However, using this code seems not to be a good practice.

Is there another solution for this problem?
 
Top