如何使用Android中的signalR在聊天应用程序中接收消息

时间:2017-11-29 17:13:22

标签: android signalr

你好我是signalR的新手我正在使用signalR制作一个聊天应用程序我在SignalR integration in android studio参考了这里的帮助我能够将消息发送到聊天组但是我无法接收消息我在这里阅读了很多Q& A但我无法解决这个问题我在这里粘贴我的代码,请任何人告诉我如何从服务器接收消息。以下是我的代码。

活动主要

   package myapp.chatapp;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.gson.JsonElement;

import java.util.ArrayList;

import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;

public class MainActivity extends AppCompatActivity implements SignalRService.Something {

    private StringBuilder mLog;

    private ListView mTestCaseList;

    private Spinner mTestGroupSpinner;

    private HubConnection mHubConnection;
    private HubProxy mHubProxy;

    private final Context mContext = this;
    private SignalRService mService;
    private SignalRService mMessageResive;
    private boolean mBound = false;

    ListView list_item;
    EditText editText;


    ArrayList<String> listItems;
    ArrayAdapter<String> adapter;

    ClientTransport transport;

    private Handler mHandler; // to display Toast message

    private Thread t;

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // don't restart the activity. Just process the configuration change
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Intent intent = new Intent();
        intent.setClass(mContext, SignalRService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);


        editText = (EditText)findViewById(R.id.edit_message);
        ImageButton btn = (ImageButton)findViewById(R.id.btn);
        list_item = (ListView)findViewById(R.id.list_item);
        listItems = new ArrayList<String>();
        /*listItems.add("First Item - added on Activity Create");*/
       /* adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, listItems);*/

        adapter = new ArrayAdapter<String>(mContext,R.layout.custom_list, R.id.textView,listItems);
        list_item.setAdapter(adapter);

        final Handler handler = new Handler();
        handler.postDelayed( new Runnable() {

            @Override
            public void run() {
                adapter.notifyDataSetChanged();
                handler.postDelayed( this, 1000 );
            }
        }, 1000 );






        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                listItems.add(editText.getText().toString());
                adapter.notifyDataSetChanged();
                sendMessage(view);
            }
        });




    }

    @Override
    protected void onStop() {
        // Unbind from the service
        if (mBound) {
            unbindService(mConnection);
            mBound = false;
        }
        super.onStop();
    }

    public void sendMessage(View view) {
        if (mBound) {

            String message = editText.getText().toString();
            String email = "kn@yopmail.com";
            String name = "Kunal From Android";
            String group ="1";
            mService.sendMessage(name,email,group,message);
            editText.setText("");
            // Call a method from the SignalRService.
            // However, if this call were something that might hang, then this request should
            // occur in a separate thread to avoid slowing down the activity performance.
            /*EditText editText = (EditText) findViewById(R.id.edit_message);
            if (editText != null && editText.getText().length() > 0) {

            }*/
        }
    }

    public void setmMessageResive(JsonElement jsonElement)
    {


        listItems.add(10, String.valueOf(jsonElement));


    }


    /**
     * Defines callbacks for service binding, passed to bindService()
     */
    private final ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            // We've bound to SignalRService, cast the IBinder and get SignalRService instance
            SignalRService.LocalBinder binder = (SignalRService.LocalBinder) iBinder;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            mBound = false;
        }
    };



    @Override
    public void doSomething(String msg) {

        listItems.add(msg);

    }
}

服务代码

    package myapp.chatapp;

import android.app.Service;
import android.bluetooth.BluetoothClass;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.JsonElement;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;

import microsoft.aspnet.signalr.client.Action;
import microsoft.aspnet.signalr.client.Credentials;
import microsoft.aspnet.signalr.client.LogLevel;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler4;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;

/**
 * Created by NULLPLEX7 on 11/28/2017.
 */

public class SignalRService extends Service {
    private HubConnection mHubConnection;
    private HubProxy mHubProxy;
    private Handler mHandler; // to display Toast message
    private final IBinder mBinder = new LocalBinder(); // Binder given to clients

    ClientTransport transport;

    registerListener registerListener;

    private MainActivity setmMessageResive;

    public  Something list;

    public SignalRService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mHandler = new Handler(Looper.getMainLooper());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int result = super.onStartCommand(intent, flags, startId);
        startSignalR();
        return result;
    }

    @Override
    public void onDestroy() {
        mHubConnection.stop();
        super.onDestroy();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // Return the communication channel to the service.
        startSignalR();
        return mBinder;
    }



    /**
     * Class used for the client Binder.  Because we know this service always
     * runs in the same process as its clients, we don't need to deal with IPC.
     */
    public class LocalBinder extends Binder {
        public SignalRService getService() {
            // Return this instance of SignalRService so clients can call public methods
            return SignalRService.this;
        }
    }

    /**
     * method for clients (activities)
     */
    public void sendMessage(String name, String email, String group, String msg ) {
        String SERVER_METHOD_SEND = "BroadCastMessage";
        mHubProxy.invoke(SERVER_METHOD_SEND, name,email,group,msg);
    }

    private void startSignalR() {
        Platform.loadPlatformComponent(new AndroidPlatformComponent());

        Credentials credentials = new Credentials() {
            @Override
            public void prepareRequest(Request request) {
                request.addHeader("User-Name", "BNK");
            }
        };

        String serverUrl = "myurlhere";
        mHubConnection = new HubConnection(serverUrl);
        mHubConnection.setCredentials(credentials);
        String SERVER_HUB_CHAT = "ChatHub";
        mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
        ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
        SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);


        mHubProxy.subscribe(this);

        transport = new LongPollingTransport(mHubConnection.getLogger());

        mHubConnection.start(transport);


          /* ****new codes here**** */
        /* ****seems useless but should be here!**** */
        mHubProxy.subscribe(new Object() {
            @SuppressWarnings("unused")
            public void newMessage(final String message, final String messageId, final String chatId,
                                   final String senderUserId, final String fileUrl, final String replyToMessageId) {


            }
        });

        try {

            signalRFuture.get();

        }catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return;
        }




        mHubProxy.on("receiveGroupMessage",
                new SubscriptionHandler4<String, String, String, String>() {
                    @Override
                    public void run(final String name,final String msg ,final String avtar,final String date ) {
                        final String finalMsg = name + " says " + msg;
                        /*final String finalMsg =  msg;*/
                        // display Toast message
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {

                                list.doSomething(msg);

                            }
                        });
                    }
                }
                , String.class,String.class,String.class,String.class);




             mHubConnection.received(new MessageReceivedHandler() {

            @Override
            public void onMessageReceived(final JsonElement json) {
                Log.e("receiveGroupMessage ", json.toString());
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), ""+json, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });



    }
    public interface Something
    {
        void doSomething(String msg);
    }

}

我读了堆栈溢出,在onMessageReceived我收到了服务器响应,但我没有得到任何响应。 我想当任何人从网上发送群组中的消息时我想在聊天应用中发送消息有人建议我需要创建事件监听器,但我不知道如何创建它。请告诉我如何在聊天应用中收到消息。

   mHubProxy.on("receiveGroupMessage",
                new SubscriptionHandler4<String, String, String, String>() {
                    @Override
                    public void run(final String name,final String msg ,final String avtar,final String date ) {
                        final String finalMsg = name + " says " + msg;
                        /*final String finalMsg =  msg;*/
                        // display Toast message
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {

                                list.doSomething(msg);

                            }
                        });
                    }
                }
                , String.class,String.class,String.class,String.class);

我以为我在这里收到了消息,但执行不在Run内部。

欢迎任何帮助

0 个答案:

没有答案