我正在尝试将套接字与 Android 连接。我知道您无法从 MainThread 打开网络连接。我创建了一个 AsyncTask 来做到这一点。我在主类中创建了私有类,我在互联网上看到了一些关于此的示例。
有人可以帮我解决问题吗?我想这是我尝试连接的方式错误,因为我已经使用普通的 Java 类连接到服务器。我已经编辑了清单以提供必要的权限。
如果有人对更好的方法有任何建议,那就太好了。
public class MainActivity extends Activity {
private ObjectInputStream input;
private ObjectOutputStream output;
private Button buttonCreateRoom;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonCreateRoom = (Button)findViewById(R.id.buttonCreate);
//buttons
buttonCreateRoom.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickButton(ConstantsRooms.CREATE_ROOM);
}
});
}
private void onClickButton(int numberButton){
RequestMessage request = null;
switch (numberButton) {
....
}
AsyncButtons asyncButtons = new AsyncButtons();
asyncButtons.execute(request);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//Botones
private class AsyncButtons extends AsyncTask<RequestMessage, ResponseMessage, Void> {
private Socket socket;
@Override
protected Void doInBackground(RequestMessage... params) {
RequestMessage request;
ResponseMessage response;
Void v = null;
try{
request = params[0];
output.writeObject(request);
output.flush();
response = (ResponseMessage)input.readObject();
...
}
@Override
protected void onPreExecute() {
try{
// Setup networking
**socket = new Socket(ConstantsRooms.SERVER_ADDRESS, ConstantsRooms.PORT_PUBLIC); -->ERROR**
socket.setTcpNoDelay(true);
output = new ObjectOutputStream(socket.getOutputStream());
output.flush();
input = new ObjectInputStream(socket.getInputStream());
}catch (Exception exp){
Log.e(TAG, "Excepcion socket ---");
exp.printStackTrace();
}
}
}
}