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(getBaseConte
Solution 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.
publicclassSocketHandler {
privatestatic Socket socket;
publicstaticsynchronized Socket getSocket(){
return socket;
}
publicstaticsynchronizedvoidsetSocket(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.
publicclassMyApplicationextendsApplication {
privateSocket socket;
publicSocketgetSocket(){
return socket;
}
publicvoidsetSocket(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:
MyApplicationapp= (MyApplication)activity.getApplication();
Socketsocket= app.getSocket();
Post a Comment for "Transfer Socket From One Activity To Another"