[英]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
属性从一个Activity
转移到另一个Activity
但我不能使用Intent.putExtra()
方法。
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? 我如何将
Socket
从一个Activity
转移到另一个Activity
?
You can't 'pass a Socket' from one Activity to another, but you do have other options. 您不能将“套接字”从一个活动传递到另一个活动,但您确实有其他选择。
Option 1 . 选项1 。 Create a class with a static reference to your Socket and access it that way.
创建一个带有对Socket的静态引用的类,并以这种方式访问它。 In your first Activity you set the Socket, which can then be accessed statically from your second Activity.
在您的第一个Activity中设置Socket,然后可以从第二个Activity中静态访问该Socket。
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. 然后,您可以通过从应用程序的任何位置调用SocketHandler.setSocket(套接字)或SocketHandler.getSocket()来访问它。
Option 2 . 选项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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.