Android:如何在所有活动中与服务器建立公共套接字连接

时间:2014-05-08 04:33:59

标签: java android sockets

我对android很新。如何与所有活动可用的服务器建立套接字连接,而不是在每个活动中建立与同一服务器的连接?

在MainActivity中,我有一个正在运行的线程,但这是其他活动无法访问的线程。

public class MainActivity extends Activity implements OnItemSelectedListener {
    private Socket socket;
    private static final int SERVERPORT = 8020;
    private static final String SERVER_IP = "192.168.1.36";

    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);

         new Thread(new ServerThread()).start();
}

class ClientThread implements Runnable {
    private Socket socket;
    private static final int SERVERPORT = 8020;
    private static final String SERVER_IP = "192.168.1.36";

    @Override
    public void run() {
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            socket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e1) {
                e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
 }

如何为所有活动提供与192.168.1.36上的服务器相同的连接,而不是在每个活动上创建连接。

编辑回答

我创建了一个存储所有连接参数的类      package com.example.clientmobile2;

 public class DataHolderClass {
 private static DataHolderClass dataObject = null;

 private DataHolderClass() {
 // left blank intentionally
 }

public static DataHolderClass getInstance() {
if (dataObject == null)
    dataObject = new DataHolderClass();
return dataObject;
}
private int server_port=8020;
private String server_ip="192.168.1.33";;

public int get_server_port() {
return server_port;
}


public String get_server_ip() {
return server_ip;
}

}

MainActivity如下: -

    public class MainActivity extends Activity implements OnItemSelectedListener {
    private static final int SERVERPORT = DataHolderClass.getInstance().get_server_port();
private static final String SERVER_IP = DataHolderClass.getInstance().get_server_ip();
     public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 
     }
     public void onClickon(View view) {
    Socket socket = null;
    try{

        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

        socket = new Socket(serverAddr, SERVERPORT);

    //sending the message to the linino as 0 to turn of the light
    PrintWriter out = new PrintWriter(new BufferedWriter(
            new OutputStreamWriter(socket.getOutputStream())),
            true);
    out.println("0"); 
    }
    catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        socket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
   }

每次点击与onClickOn关联的按钮时,应用程序都会崩溃。

错误记录

05-08 10:38:40.171: E/AndroidRuntime(12909): FATAL EXCEPTION: main
05-08 10:38:40.171: E/AndroidRuntime(12909): Process: com.example.clientmobile2, PID: 12909
05-08 10:38:40.171: E/AndroidRuntime(12909): java.lang.IllegalStateException: Could not execute method of the activity
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View$1.onClick(View.java:3841)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View.performClick(View.java:4456)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View$PerformClick.run(View.java:18462)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.os.Handler.handleCallback(Handler.java:733)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.os.Handler.dispatchMessage(Handler.java:95)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.os.Looper.loop(Looper.java:136)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.app.ActivityThread.main(ActivityThread.java:5102)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at dalvik.system.NativeStart.main(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909): Caused by: java.lang.reflect.InvocationTargetException
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invokeNative(Native Method)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at java.lang.reflect.Method.invoke(Method.java:515)
05-08 10:38:40.171: E/AndroidRuntime(12909):    at android.view.View$1.onClick(View.java:3836)
05-08 10:38:40.171: E/AndroidRuntime(12909):    ... 11 more
05-08 10:38:40.171: E/AndroidRuntime(12909): Caused by: java.lang.NullPointerException
05-08 10:38:40.171: E/AndroidRuntime(12909):    at com.example.clientmobile2.MainActivity.onClickon(MainActivity.java:331)

2 个答案:

答案 0 :(得分:0)

你可以创建一个singleton class并在那里定义那个对象,或者使用android提供的application类,然后在那里定义你的套接字对象。然后在所有活动中都可以访问你的对象。 read here如何使用Application类。

答案 1 :(得分:0)

在这种情况下你必须使用SINGLETON CLASS。从你的第一个屏幕你必须设置信用,然后你可以在任何屏幕上获取它们。你可以使用下面的代码:

public class DataHolderClass {
private static DataHolderClass dataObject = null;

private DataHolderClass() {
    // left blank intentionally
}

public static DataHolderClass getInstance() {
    if (dataObject == null)
        dataObject = new DataHolderClass();
    return dataObject;
}
    private int server_port;
private String server_ip;

    public String get_server_port() {
    return server_port;
}

public void set_server_port(String server_port) {
    this._server_port = server_port;
}

    public String get_server_ip() {
    return server_ip;
}

public void set_server_ip(String server_ip) {
    this.server_ip= server_ip;
}

}

现在,在您的活动中,您必须设置如下所示的值:

DataHolderClass.getInstance().set_server_port("8020");
DataHolderClass.getInstance().set_server_ip("192.168.1.36");

现在要在代码下面使用值:

 String a = DataHolderClass.getInstance().get_server_port();
String b = DataHolderClass.getInstance().get_server_ip();