basic4android android.os.networkonmainthreadexception错误

时间:2015-01-13 03:22:13

标签: basic4android

我正在尝试使用我的Android设备控制LED,我正在使用Basic4android作为应用程序。我的工作正常,但每次我按下按钮打开/关闭LED ..我收到此错误说" android.os.NetworkOnMainThreadException" ......这是我的代码:

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
     Dim request As HttpRequest
     Dim HttpClient1 As HttpClient
End Sub

 Sub Globals
'These global variables will be redeclared each time the activity is created.
'These variables can only be accessed from this module.

    Dim Button1 As Button
    Dim Button2 As Button
    Dim Button3 As Button
    Dim Button4 As Button
    Dim Button5 As Button
    Dim Button6 As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    Activity.LoadLayout("main")
    HttpClient1.Initialize("HttpClient1")
End Sub

Sub HttpClient1_ResponseSuccess (Response As HttpResponse, TaskId As Int)
    Dim resultString As String
    resultString = Response.GetString("UTF8")
End Sub

Sub HttpClient1_ResponseError (Response As HttpResponse, Reason As String, StatusCode As Int,     TaskId As Int)
    Log("Error connecting: " & Reason &" "& StatusCode)
    If Response <> Null Then
    Log(Response.GetString("UTF8"))
    Response.Release
    End If
End Sub

Sub Button6_Click
  request.InitializeGet("http://192.168.0.8/?BlueOFF")
  HttpClient1.Execute(request, 1)
End Sub

Sub Button5_Click
   request.InitializeGet("http://192.168.0.8/?BlueON")
   HttpClient1.Execute(request, 1)
End Sub

Sub Button4_Click
  request.InitializeGet("http://192.168.0.8/?GreenOFF")
  HttpClient1.Execute(request, 1)
End Sub

Sub Button3_Click
    request.InitializeGet("http://192.168.0.8/?GreenON")
    HttpClient1.Execute(request, 1)
End Sub

Sub Button2_Click
    request.InitializeGet("http://192.168.0.8/?RedOFF")
    HttpClient1.Execute(request, 1)
End Sub

Sub Button1_Click
    request.InitializeGet("http://192.168.0.8/?RedON")
    HttpClient1.Execute(request, 1)
End Sub

我已经研究过这个问题,它说我正在主线程上进行网络操作......我是basic4android的新手......有关如何进行网络操作的任何提示一个单独的线程?任何帮助真的很感激..谢谢你:D

最好的问候, 考德威尔。

1 个答案:

答案 0 :(得分:1)

有两种解决方案。最简单的方法是在Android版本更高的API 9上禁用严格模式:

Sub DisableStrictMode
   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
End Sub

更好的解决方案是使用Asynchronous Response.GetAschronchron()调用替换Response.GetString()调用(不推荐使用)。