如何从Service连接套接字并告诉Fragment已连接套接字

时间:2019-05-14 09:55:12

标签: android android-fragments android-activity socket.io android-service

我从Application到Fragment类这样调用方法:

ChatApplication app = (ChatApplication) getActivity().getApplication(); mSocket = app.getSocket();

,我得到了mSocket的连接。 如何使用Service代替Application来实现相同功能? Fragment需要套接字连接才能启动其他操作。我需要连接才能处于服务状态,而不是处于Fragment或其他状态。

ChatApplication.java

package com.github.nkzawa.socketio.androidchat;

import android.app.Application;
import io.socket.client.IO;
import io.socket.client.Socket;

import java.net.URISyntaxException;

public class ChatApplication extends Application {

    private Socket mSocket;
    {
        try {
            mSocket = IO.socket(Constants.CHAT_SERVER_URL);
            mSocket.connect();
        } catch (URISyntaxException e) {
            throw new RuntimeException(e);
        }
    }

    public Socket getSocket() {
        return mSocket;
    }
}

MainFragment.java

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setHasOptionsMenu(true);

        ChatApplication app = (ChatApplication) getActivity().getApplication();
        mSocket = app.getSocket();

        startSignIn();
    }

0 个答案:

没有答案