我对android中的服务(远程服务)中的主线程感兴趣。我用 2 个线程实现了服务(一个用于从套接字读取,一个用于从同一个套接字向服务器发送数据)。当我想开始连接时(我只从“读取”线程的内部进行,如果它通过,则设置特殊标志以通知“发送”线程已设置连接)我收到如下错误:
02-19 18:12:46.318: E/AndroidRuntime(4945): FATAL EXCEPTION: main
02-19 18:12:46.318: E/AndroidRuntime(4945): android.os.NetworkOnMainThreadException
02-19 18:12:46.318: E/AndroidRuntime(4945): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
02-19 18:12:46.318: E/AndroidRuntime(4945): at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
02-19 18:12:46.318: E/AndroidRuntime(4945): at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.io.InputStreamReader.read(InputStreamReader.java:244)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.io.BufferedReader.fillBuf(BufferedReader.java:130)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.io.BufferedReader.readLine(BufferedReader.java:354)
02-19 18:12:46.318: E/AndroidRuntime(4945): at com.example.aaa.MyService.try_to_connect_with_server(MyService.java:640)
02-19 18:12:46.318: E/AndroidRuntime(4945): at com.example.aaa.MyService.URUCHOM_SIEC(MyService.java:510)
02-19 18:12:46.318: E/AndroidRuntime(4945): at com.example.aaa.MyService$Handler_X.handleMessage(MyService.java:219)
02-19 18:12:46.318: E/AndroidRuntime(4945): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 18:12:46.318: E/AndroidRuntime(4945): at android.os.Looper.loop(Looper.java:137)
02-19 18:12:46.318: E/AndroidRuntime(4945): at android.app.ActivityThread.main(ActivityThread.java:5039)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.lang.reflect.Method.invokeNative(Native Method)
02-19 18:12:46.318: E/AndroidRuntime(4945): at java.lang.reflect.Method.invoke(Method.java:511)
02-19 18:12:46.318: E/AndroidRuntime(4945): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-19 18:12:46.318: E/AndroidRuntime(4945): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-19 18:12:46.318: E/AndroidRuntime(4945): at dalvik.system.NativeStart.main(Native Method)
在下面这样的代码中(在 in.readline 行中):
...
socket.connect(new InetSocketAddress(ADRES, 6000), 1200);
if (socket != null) {
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream()));
out.write("login_message\n");
out.flush();
response = in.readLine(); //<<<===== errors occur here
...
//setting flags about established connection
}
我不明白什么是主线程(在这种情况下),为什么有时会出现这些错误?如果我的问题是基本的,我深表歉意,但我无法(我)找到理解答案。我添加了简单而难看的流量控制图(我是业余爱好者):
问候, 阿蒂克