Android client for SignalR does not receive but JS does

我怕爱的太早我们不能终老 提交于 2019-12-05 13:47:52

You can refer to my following sample code. I have tested. Hope this helps!

public class MainActivity extends AppCompatActivity {

private TextView mTextView;
private final Context mContext = this;
private Handler mHandler;

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

    mTextView = (TextView) findViewById(R.id.textView);

    mHandler = new Handler(Looper.getMainLooper());

    Platform.loadPlatformComponent(new AndroidPlatformComponent());
    Credentials credentials = new Credentials() {
        @Override
        public void prepareRequest(Request request) {
            request.addHeader("User-Name", "BNK");
        }
    };
    String serverUrl = "http://192.168.1.100/signalr";
    HubConnection connection = new HubConnection(serverUrl);
    connection.setCredentials(credentials);
    HubProxy hubProxy = connection.createHubProxy("ChatHub");
    ClientTransport clientTransport = new ServerSentEventsTransport(connection.getLogger());
    SignalRFuture<Void> awaitConnection = connection.start(clientTransport);
    try {
        awaitConnection.get();
    } catch (InterruptedException | ExecutionException e) {
        Log.e("SignalR", e.toString());
        e.printStackTrace();
        return;
    }

    hubProxy.on("SimpleMessage", new SubscriptionHandler1<String>() {
        @Override
        public void run(final String s) {
            Log.i("SignalR", s);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mTextView.setText(mTextView.getText() + "\n" + s);
                    Toast.makeText(mContext, "message recieved: " + s, Toast.LENGTH_LONG).show();
                }
            });
        }
    }, String.class);
}

...
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!