Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 964
Greenvein Avatar asked Apr 23 '14 15:04

Greenvein


1 Answers

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();
like image 120
Cruceo Avatar answered Oct 21 '22 14:10

Cruceo