Transfer Socket from one Activity to another

二次信任 提交于 2020-01-01 02:33:07

问题


I am trying to transfer Socket attribute from one Activity to another but i can not use Intent.putExtra() method.

socket = new Socket("10.0.0.9", port);
i = new Intent(getBaseContext(), MainActivity.class);
i.putExtra("mysocket", socket);

How i can transfer Socket from one Activity to another?


回答1:


You can't 'pass a Socket' from one Activity to another, but you do have other options.

Option 1. Create a class with a static reference to your Socket and access it that way. In your first Activity you set the Socket, which can then be accessed statically from your second Activity.

Eg.

public class SocketHandler {
    private static Socket socket;

    public static synchronized Socket getSocket(){
        return socket;
    }

    public static synchronized void setSocket(Socket socket){
        SocketHandler.socket = socket;
    }
}

You can then access it by calling SocketHandler.setSocket(socket) or SocketHandler.getSocket() from anywhere throughout your app.

Option 2. Override the Application and have a global reference to the socket in there.

Eg.

public class MyApplication extends Application {
    private Socket socket;

    public Socket getSocket(){
        return socket;
    }

    public void setSocket(Socket socket){
        SocketHandler.socket = socket;
    }
}

This option will require you to point to your Application in the manifest file. In your manifest's application tag, you need to add:

android:name="your.package.name.MyApplication"

You can then access it by getting a reference to the Application in your Activity:

MyApplication app = (MyApplication)activity.getApplication();
Socket socket = app.getSocket();


来源:https://stackoverflow.com/questions/23249163/transfer-socket-from-one-activity-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!