我正在尝试创建一个充当Web Socket服务器的Android应用程序。这是我的MainActivity.java。
package com.example.websocket;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import org.apache.http.conn.util.InetAddressUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText port, msg;
Button listen, send;
TextView status;
int p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
port = (EditText)findViewById(R.id.editText1);
msg = (EditText)findViewById(R.id.editText2);
listen = (Button)findViewById(R.id.button1);
send = (Button)findViewById(R.id.button2);
status = (TextView)findViewById(R.id.textView1);
listen.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
String temp = port.getText().toString();
p = Integer.parseInt(temp);
try
{
custom_web_socket wsocket = new custom_web_socket(p);
wsocket.start();
}
catch (UnknownHostException e) {
e.printStackTrace();
}
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class custom_web_socket extends WebSocketServer
{
public custom_web_socket(int port_add) throws UnknownHostException {
super(new InetSocketAddress(port_add));
// pass
}
@Override
public void onClose(WebSocket arg0, int arg1, String arg2, boolean arg3) {
status.setText("Connection closed.");
}
@Override
public void onError(WebSocket arg0, Exception arg1) {
status.setText((CharSequence) arg1);
}
@Override
public void onMessage(WebSocket arg0, String arg1) {
// TODO Auto-generated method stub
}
@Override
public void onOpen(WebSocket arg0, ClientHandshake arg1) {
status.setText("Connected");
}
}
}
运行程序时,应用程序启动。但是,当我尝试在EditText字段中输入值时,应用程序会挂起并结束。我将此示例称为Web套接字 - https://github.com/TooTallNate/Java-WebSocket/blob/master/src/main/example/ChatServer.java
我已经导入了必要的jar文件。这是我第一次尝试android编程,我不确定问题是什么。
答案 0 :(得分:0)
您正在使用onClick事件。 因此,无论何时尝试输入内容,都会调用您的方法。并挂断电话。
当用户输入完代码后,您的操作就会发生。 您可以使用以下代码
port.setOnEditorActionListener(
new EditText.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent
event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode()==KeyEvent.KEYCODE_ENTER)
{
if (!event.isShiftPressed()) {
// the user is done typing.
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
另请参阅http://developer.android.com/reference/android/widget/EditText.html 你会得到清晰的想法。