所以我正在开发一个涉及套接字的应用程序。多个字符串通过套接字发送,接收端接收它,并相应地更新RecyclerView
。一切正常,直到应用程序崩溃/重新启动。我不知道会发生什么,但是Play商店中有一个名为XRecorder的应用程序,每次我使用屏幕截图功能时,我的应用程序都会重新启动。现在,当我通过套接字发送消息时,它会收到消息,但是不会更新RecyclerView吗?出现Toast
的原因是我知道收到它的原因。当我致电removeItem()
这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
serverAsync.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private class ServerAsync extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
try {
serverSocket = new ServerSocket(serverPort);
while (true) {
Socket client = serverSocket.accept();
isConnected = client.isConnected();
if (isConnected) {
try {
handler.post(new Runnable() {
@Override
public void run() {
updateStatusUI();
}
});
Entry entry = new Entry();
String inputLine;
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
while ((inputLine = in.readLine()) != null) {
StringBuilder sb = new StringBuilder();
String message = inputLine;
sb.append(message);
entry.add(sb.toString());
}
//READ NEW ENTRIES
handler.post(new Runnable() {
@Override
public void run() {
splitOrder(entry);
saveArrayList();
}
});
in.close();
handler.post(new Runnable() {
@Override
public void run() {
entryAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "In has closed :" + client.getRemoteSocketAddress(), Toast.LENGTH_SHORT).show();
updateStatusUI();
}
});
} catch (Exception e) {
Log.e("TEST", e.getMessage(), e);
}
} else {
Toast.makeText(getApplicationContext(), "Client :" + client.getRemoteSocketAddress()+" has DISCONNECTED", Toast.LENGTH_SHORT).show();
handler.post(new Runnable() {
@Override
public void run() {
updateStatusUI();
}
});
}
}
} catch (Exception e) {
Log.e("UHE", e.getMessage(), e);
}
return null;
}
}
public void removeItem(int position) {
entryAdapter.notifyDataSetChanged();
}
我曾尝试为RecyclerView
重置适配器,但是那根本行不通。我还注意到,每次应用崩溃并重新启动时,我都会收到java.net.BindException: bind failed: EADDRINUSE (Address already in use)
指向创建我的serverSocket (serverSocket = new ServerSocket(serverPort)
这可能是RecyclerView无法更新的原因吗? ArrayList可以使用传入消息进行更新,而不能使用视图进行更新。