@blog.justoneplanet.info

日々勉強

AndroidでWebSocket接続する

素晴らしいライブラリのお陰で5分で接続できる。

■Activityで使う

package info.justoneplanet.android.eew;
import java.net.URI;
import java.net.URISyntaxException;
import org.java_websocket.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class EarthquakeEarlyWarningActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try {
            URI uri = new URI("ws", null, "123.123.123.123", 443, "/", null, null);
            WebSocketClient c = new WebSocketClient(uri, new Draft_17()) {
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.e("onOpen", handshakedata.toString());
                }
                @Override
                public void onMessage(String message) {
                    Log.e("onMessage", message);
                }
                @Override
                public void onError(Exception ex) {
                    Log.e("onError", ex.toString());
                }
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    Log.e("onClose", reason.toString());
                }
            };
            c.connect();
        }
        catch (URISyntaxException e) {
            e.printStackTrace();
        }
   }
}

あとは以下のパーミッションを付加する。

<uses-permission android:name="android.permission.INTERNET" />

■AppWidgetなどで使う

メインスレッド以外で使うには以下のようにする。

package info.justoneplanet.android.eew;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Random;

import org.java_websocket.WebSocketClient;
import org.java_websocket.drafts.Draft_17;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

public class Widget extends AppWidgetProvider {
    private WebSocketClient client;
    private HandlerThread sWorkerThread;
    private Handler sWorkerQueue;
    private Server[] mServers;
    
    private class Server {
        String host;
        int port;
        public Server(String host, int port) {
            this.host = host;
            this.port = port;
        }
    }
    
    public Widget() {
        super();
        sWorkerThread = new HandlerThread("Widget-worker");
        sWorkerThread.start();
        sWorkerQueue = new Handler(sWorkerThread.getLooper());
        mServers = new Server[]{
                new Server("123.123.123.123", 80)
        };
    }
    
    @Override
    public void onEnabled(final Context context) {
        super.onEnabled(context);
    }
    
    @Override
    public void onUpdate(final Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        super.onUpdate(context, appWidgetManager, appWidgetIds);
        Log.e("onUpdate", "onUpdate");
        sWorkerQueue.removeMessages(0);
        try {
            Random rand = new Random();
            Server server = mServers[rand.nextInt(mServers.length) % mServers.length];
            URI uri = new URI("ws", null, server.host, server.port, "/", null, null);
            sWorkerQueue.post(new WebSocketClient(uri, new Draft_17()) {
                private String chunk;
                private RemoteViews remoteViews;
                
                @Override
                public void onOpen(ServerHandshake handshakedata) {
                    Log.e("onOpen", handshakedata.toString());
                    Toast.makeText(context, handshakedata.toString(), Toast.LENGTH_LONG);
                    remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
                }
                
                @Override
                public void onMessage(String message) {
                    Log.e("onMessage", message);
                    remoteViews.setTextViewText(R.id.info, context.getString(R.string.connected));
                    ComponentName componentName = new ComponentName(context, Widget.class);
                    AppWidgetManager manager = AppWidgetManager.getInstance(context);
                    manager.updateAppWidget(componentName, remoteViews);
                }
                
                @Override
                public void onError(Exception ex) {
                    Log.e("onError", ex.toString());
                    remoteViews.setTextViewText(R.id.info, ex.toString());
                }
                
                @Override
                public void onClose(int code, String reason, boolean remote) {
                    Log.e("onClose", reason);
                    remoteViews.setTextViewText(R.id.info, reason);
                    client.connect();
                }
            });
        }
        catch (URISyntaxException e1) {
            e1.printStackTrace();
        }
    }
}

再接続処理とかしないといけない。こちらのライブラリを使っても上述と同様に面倒な記述が必要である。

2 Comments»

good

RSS feed for comments on this post.TrackBack URL

Leave a comment