我正在尝试构建一个不断从运行 dump1090 的服务器读取 SBS-1 数据的应用程序。我认为我最好使用 Service 而不是 AsyncTask 这样做,因为至少它的生命周期将独立于 UI 组件,而且 AFAIK AsyncTasks 应该用于短期操作。
这是我的代码:
@Override
public void onCreate() {
super.onCreate();
try {
//TODO: NetworkOnMainThread error
socket = new Socket(SERVER_URL, SERVER_PORT);
socketConnected = true;
inputStream = socket.getInputStream();
diStream = new DataInputStream(inputStream);
readerOpen = true;
ConnectSocket connectSocket = new ConnectSocket();
Log.d(getClass().toString(), "Socket created!");
} catch (IOException e) {
e.printStackTrace();
}
}
但是,一旦我启动应用程序,就会发生这种情况:
FATAL EXCEPTION: main
Process: com.example.[APP_NAME], PID: 2317
java.lang.RuntimeException: Unable to create service com.example.[APP_NAME].services.SocketService: android.os.NetworkOnMainThreadException
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2887)
at android.app.ActivityThread.-wrap4(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1427)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1273)
at java.net.InetAddress.lookupHostByName(InetAddress.java:431)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at java.net.Socket.tryAllAddresses(Socket.java:109)
at java.net.Socket.<init>(Socket.java:178)
at java.net.Socket.<init>(Socket.java:150)
at com.example.[APP_NAME].services.SocketService.onCreate(SocketService.java:50)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2877)
at android.app.ActivityThread.-wrap4(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1427)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我究竟做错了什么?我需要添加一个新线程来运行我的服务吗?