Last active
January 20, 2016 09:44
-
-
Save laserpants/e84b62d1109d457517c4 to your computer and use it in GitHub Desktop.
WebSocket service class.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.farmradio.fessbox; | |
import android.app.Service; | |
import android.content.Intent; | |
import android.os.Binder; | |
import android.os.IBinder; | |
import android.support.annotation.Nullable; | |
import android.util.Log; | |
import de.tavendo.autobahn.WebSocketConnection; | |
import de.tavendo.autobahn.WebSocketException; | |
import de.tavendo.autobahn.WebSocketHandler; | |
public class WebSocketService extends Service { | |
private final IBinder binder = new WebSocketServiceBinder(); | |
private WebSocketConnection connection = new WebSocketConnection(); | |
private WebSocketMessageListener listener; | |
@Nullable | |
@Override | |
public IBinder onBind(Intent intent) { | |
return binder; | |
} | |
@Override | |
public void onCreate() { | |
super.onCreate(); | |
try { | |
connection.connect("ws://fessbox.local:19998", new WebSocketHandler() { | |
@Override | |
public void onOpen() { | |
Log.d("FessBox", "WebSocket connection established."); | |
} | |
@Override | |
public void onTextMessage(String payload) { | |
if (listener != null) { | |
listener.onMessage(payload); | |
} | |
} | |
@Override | |
public void onClose(int code, String reason) { | |
Log.d("FessBox", "WebSocket connection lost: " + reason); | |
} | |
}); | |
} catch (WebSocketException exception) { | |
Log.e("FessBox", exception.toString()); | |
} | |
} | |
@Override | |
public void onDestroy() { | |
super.onDestroy(); | |
connection.disconnect(); | |
} | |
public void sendTextMessage(String message) { | |
connection.sendTextMessage(message); | |
} | |
public void sendBinaryMessage(byte[] bytes) { | |
connection.sendBinaryMessage(bytes); | |
} | |
public class WebSocketServiceBinder extends Binder { | |
public WebSocketService getService() { | |
return WebSocketService.this; | |
} | |
public void setListener(WebSocketMessageListener listener) { | |
WebSocketService.this.listener = listener; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment