将套接字从一个活动转移到另一个活动

将套接字从一个活动转移到另一个活动

本文介绍了将套接字从一个活动转移到另一个活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Socket属性从一个Activity转移到另一个Activity,但是我不能使用Intent.putExtra()方法.

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

我如何将Socket从一个Activity转移到另一个?

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.

选项1 .创建一个具有静态引用的Socket类,然后以这种方式访问​​它.在您的第一个活动中设置套接字,然后可以从第二个活动中静态访问该套接字.

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.

例如.

public class SocketHandler {
    private static Socket socket;

    public static synchronized Socket getSocket(){
        return socket;
    }

    public static synchronized void setSocket(Socket socket){
        SocketHandler.socket = socket;
    }
}

然后您可以通过在整个应用中的任何位置调用SocketHandler.setSocket(socket)或SocketHandler.getSocket()来访问它.

You can then access it by calling SocketHandler.setSocket(socket) or SocketHandler.getSocket() from anywhere throughout your app.

选项2 .覆盖应用程序,并在其中对套接字进行全局引用.

Option 2. Override the Application and have a global reference to the socket in there.

例如.

public class MyApplication extends Application {
    private Socket socket;

    public Socket getSocket(){
        return socket;
    }

    public void setSocket(Socket socket){
        SocketHandler.socket = socket;
    }
}

此选项将要求您指向清单文件中的应用程序".在清单的application标记中,您需要添加:

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

这篇关于将套接字从一个活动转移到另一个活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 01:42