简体   繁体   中英

Transfer Socket from one Activity to another

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM