我有一个由eclipse创建的android应用程序。 此应用程序用作通过套接字连接无线连接到服务器的客户端。 我有套接字创建代码的问题。 当我尝试在我的应用程序中将代码从活动移动到另一个活动时,它就不起作用了。
以下是代码工作的第一个活动:
public class MyNewAndroidActivity extends Activity {
protected Socket socket;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button_connect = (Button) findViewById(R.id.button1);
final Button button_disconnect = (Button) findViewById(R.id.button2);
final Button b_forward = (Button) findViewById(R.id.b_forward);
final Button b_backward = (Button) findViewById(R.id.b_backward);
final Button b_right = (Button) findViewById(R.id.b_right);
final Button b_left = (Button) findViewById(R.id.b_left);
final Button b_stop = (Button) findViewById(R.id.b_stop);
button_connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Create socket with time out
//192.168.1.76
// my code which I want to transfer it.
int port = 2005;
SocketAddress sockaddr = new InetSocketAddress("192.168.1.15", port);
socket = new Socket();
int timeoutMs = 2000;
socket.connect(sockaddr, timeoutMs);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
当我将其转换为另一个活动中的方法时,它不起作用:
public class IBMEyes extends Activity implements SensorListener{
protected static Socket socket;
final String tag = "MyProject";
String state ="off";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
Button b_connect = (Button) findViewById(R.id.button1);
b_connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SocketConnect();
}
});
// here is my code that I've transferred it.
public void SocketConnect() {
// TODO Auto-generated method stub
try {
int port = 2005;
SocketAddress sockaddr = new InetSocketAddress("192.168.1.15", port);
socket = new Socket();
int timeoutMs = 2000;
socket.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}