Transferring a socket from one operation to another

I am trying to pass the Socket attribute from one Activity to another, but I cannot use the Intent.putExtra() method.

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

How can I transfer a Socket from one Activity to another?

+6
source share
1 answer

You cannot pass Socket from one action to another, but you have other options.

Option 1 Create a class with a static link to your Socket and access it that way. In the first action, you install Socket, which can then be statically retrieved from your second action.

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 in your application.

Option 2 Redefine the application and get a global socket link.

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 the application manifest tag, you need to add:

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

Then you can access it by receiving a link to the application in your activity:

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

All Articles