使用SignalR推送服务在Android的实现 SignalA
由于我的版本最低是2.2,所以只有把源码下下来自己改,如果你觉得太多了可自己编译成jar引用,本人不才,对java不是很熟悉,如果此版本中有错误还请大家指出来,此图显示的是安卓2.2与4.0的版本。
chat_hub代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <EditText android:id="@+id/chat_text" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="20dp" android:gravity="top" android:inputType="textMultiLine" android:text="" /> </LinearLayout>
ChatHub.java代码:
package com.loan.zhironghuimobile; import org.json.JSONArray; import com.zsoft.SignalA.Hubs.HubConnection; import com.zsoft.SignalA.Hubs.HubOnDataCallback; import com.zsoft.SignalA.Hubs.IHubProxy; import com.zsoft.SignalA.Transport.StateBase; import com.zsoft.SignalA.Transport.Longpolling.LongPollingTransport; import android.app.Activity; import android.content.OperationApplicationException; import android.os.Bundle; import android.widget.EditText; public class ChatHub extends Activity { private final static String HUB_URL="http://192.168.1.200:82/signalr/hubs"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.chat_hub); beginConnect(); } /** * hub链接 */ private HubConnection conn=new HubConnection(HUB_URL, this, new LongPollingTransport()) { @Override public void OnError(Exception exception) { } @Override public void OnMessage(String message) { } @Override public void OnStateChanged(StateBase oldState, StateBase newState) { } }; /** * hub代理 panderman 2013-10-25 */ private IHubProxy hub = null; /** * 开启推送服务 panderman 2013-10-25 */ private void beginConnect(){ try { hub=conn.CreateHubProxy("ChatHub"); } catch (OperationApplicationException e) { e.printStackTrace(); } hub.On("addNewMessageToPage", new HubOnDataCallback() { @Override public void OnReceived(JSONArray args) { EditText chatText=(EditText)findViewById(R.id.chat_text); //chatText.setText(args.toString()); for(int i=0; i<args.length(); i++) { chatText.append(args.opt(i).toString()); } } }); conn.Start(); } }
SignalR服务器端代码参照http://www.asp.net/signalr来写
赞 (0)