Skip to content

Instantly share code, notes, and snippets.

@secobarbital
Created December 5, 2012 23:01
Show Gist options
  • Save secobarbital/4220309 to your computer and use it in GitHub Desktop.
Save secobarbital/4220309 to your computer and use it in GitHub Desktop.
Socket.IO with Android WebView
class BridgeCallback implements IOAcknowledge, IOCallback {
...
@Override
public void ack(Object... args) {
String argsStr = TextUtils.join(",", args);
final String callback = "javascript:" + mCallback + "(" + argsStr + ");";
((MainActivity)mContext).runOnUiThread(new Runnable() {
public void run() {
mWebView.loadUrl(callback);
}
});
}
...
if Android?
window.socketCallbacks = {}
window.socket = Backbone.socket = #Android.socket()
on: (event, cb) ->
window.socketCallbacks[event] = cb
emit: (event, data, cb) ->
functionName = 'cb' + Math.floor(Math.random()*100000000000000000)
if typeof data == 'function'
cb = data
data = null
window[functionName] = cb
Android.emit event, JSON.stringify(data), "window.#{functionName}"
mWebView.addJavascriptInterface(new JavaScriptInterface() {
public void emit(String event, String data, String callback) {
if("null".equals(data)) {
mSocket.emit(event, new BridgeCallback(mWebView, mContext, callback));
} else {
Object json = null;
try {
json = new JSONObject(data);
} catch (JSONException e) {
try {
json = new JSONArray(data);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
mSocket.emit(event, new BridgeCallback(mWebView, mContext, callback), json);
}
}
}, "Android");
mWebView.setWebViewClient(new android.webkit.WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
SocketIO socket;
try {
socket = new SocketIO(hostUri.toString());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socket.connect(new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
@Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
@Override
public void onConnect() {
System.out.println("Connection established");
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
new BridgeCallback(mWebView, this, "window.socketCallbacks[\"" + event + "\"]").ack(args);
mWebView.loadUrl(callback);
}
});
}
@adus80
Copy link

adus80 commented Sep 27, 2013

Could I have a complete example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment