如何将数据从socket.io服务传输到活动

时间:2016-06-13 02:59:11

标签: android node.js sockets android-service

目前,我有一个Service,应该为多个不同的Activity开放socket.io连接。该应用程序最大的功能之一是每当歌曲添加到播放列表时更新专辑封面图库。如果添加了歌曲,Node.js服务器会广播,我的目标是SocketService在触发.on("song added"...时更新UI。但是,目前,我无法弄清楚如何将传入数据从SocketService传输到用户界面。我该怎么做呢?

供参考:

来自服务器的"song add"命令会发出JSONObject

public class SocketService extends IntentService {
Socket socket;
String roomID;
String userID;
ArrayList<JSONObject> queuedSongs;
ArrayList<JSONObject> suggestionSongs;
int users;

public SocketService() {
    super("SocketService");
}



@Override
protected void onHandleIntent(Intent intent) {
    userID = intent.getExtras().getString("userid", "0");
    Log.i("SocketService", "userID=" + userID);
    roomID = intent.getExtras().getString("code");
    Log.i("SocketService", "roomID=" + roomID);
    super.onCreate();
    try {
        socket = IO.socket("server address");
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Log.i("Internet-Task", "Connected to "server address"");
            }

        }).on("song add", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    suggestionSongs.add(new JSONObject(args[0].toString()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        //**//

        socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                Transport transport = (Transport) args[0];

                transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
                    @Override
                    public void call(Object... args) {
                        @SuppressWarnings("unchecked")
                        Map<String, List<String>> headers = (Map<String, List<String>>) args[0];
                        // modify request headers
                        headers.put("userid", Arrays.asList(userID));
                        headers.put("roomid", Arrays.asList(roomID));
                    }
                });
        socket.connect();
    } catch (URISyntaxException e) {
        Log.e(getClass().getCanonicalName(), e.toString());
    }

此外,这是对Activity onCreate()中所做服务的调用。之前没有新线程。

protected void onCreate(Bundle savedInstanceState) {

...

    Intent serviceIntent = new Intent(getBaseContext(), SocketService.class);
    Bundle serviceBundle = new Bundle();
    serviceBundle.putString("code", roomID);;
    serviceBundle.putString("userid", userID);
    serviceIntent.putExtras(mBundle);
    startService(serviceIntent);

同样,我的问题是:如何将数据从SocketService传输到Activity的用户界面?

0 个答案:

没有答案