android websocket構建客戶端

一、添加依賴 implementation "org.java-websocket:Java-WebSocket:1.4.0"java

二、配置三個類
android

(1)JWebSocketClientweb

public class JWebSocketClient extends WebSocketClient {
    public JWebSocketClient(URI serverUri) {
        super(serverUri, new Draft_6455());
    }

    @Override
    public void onOpen(ServerHandshake handshakedata) {
        Log.e("JWebSocketClient", "onOpen()");
    }

    @Override
    public void onMessage(String message) {
        Log.e("JWebSocketClient", "onMessage()");
    }

    @Override
    public void onClose(int code, String reason, boolean remote) {
        Log.e("JWebSocketClient", "onClose()");

    }

    @Override
    public void onError(Exception ex) {
        Log.e("JWebSocketClient", "onError()");
    }
}
複製代碼

(2)JWebSocketClientServicebash

public class JWebSocketClientService extends Service {
    public JWebSocketClient client;
    private JWebSocketClientBinder mBinder = new JWebSocketClientBinder();
    private final static int GRAY_SERVICE_ID = 1001;
    //灰色保活
    public static class GrayInnerService extends Service {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            startForeground(GRAY_SERVICE_ID, new Notification());
            stopForeground(true);
            stopSelf();
            return super.onStartCommand(intent, flags, startId);
        }
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
    PowerManager.WakeLock wakeLock;//鎖屏喚醒
    //獲取電源鎖,保持該服務在屏幕熄滅時仍然獲取CPU時,保持運行
    @SuppressLint("InvalidWakeLockTag")
    private void acquireWakeLock()
    {
        if (null == wakeLock)
        {
            PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, "PostLocationService");
            if (null != wakeLock)
            {
                wakeLock.acquire();
            }
        }
    }

    //用於Activity和service通信
    public class JWebSocketClientBinder extends Binder {
        public JWebSocketClientService getService() {
            return JWebSocketClientService.this;
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //初始化websocket
        initSocketClient();
        mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//開啓心跳檢測

        //設置service爲前臺服務,提升優先級
//        if (Build.VERSION.SDK_INT < 18) {
//            //Android4.3如下 ,隱藏Notification上的圖標
//            startForeground(GRAY_SERVICE_ID, new Notification());
//        } else if(Build.VERSION.SDK_INT>18 && Build.VERSION.SDK_INT<25){
//            //Android4.3 - Android7.0,隱藏Notification上的圖標
//            Intent innerIntent = new Intent(this, GrayInnerService.class);
//            startService(innerIntent);
//            startForeground(GRAY_SERVICE_ID, new Notification());
//        }else{
//            //Android7.0以上app啓動後通知欄會出現一條"正在運行"的通知
////            startForeground(GRAY_SERVICE_ID, new Notification());
//        }

        acquireWakeLock();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        closeConnect();
        super.onDestroy();
    }

    public JWebSocketClientService() {
    }
    /**
     * 初始化websocket鏈接
     */
    private void initSocketClient() {
        URI uri = URI.create(WebSocketUtil.ws);
        client = new JWebSocketClient(uri) {
            @Override
            public void onMessage(String message) {
                Log.e("onmessage1111111", message);
                    if(!message.equals("server...Leave...")) {
                        EventBus.getDefault().post(new MessageEvent(message));
                    }

//                Intent intent = new Intent();
//                intent.setAction("com.xch.servicecallback.content");
//                intent.putExtra("message", message);
//                sendBroadcast(intent);

//                checkLockAndShowNotification(message);
            }

            @Override
            public void onOpen(ServerHandshake handshakedata) {
                super.onOpen(handshakedata);
                Log.e("JWebSocketClientService", "websocket鏈接成功");
                ToastUtils.showShort("websocket鏈接成功");

            }

            @Override
            public void onError(Exception ex) {
                super.onError(ex);
                ToastUtils.showShort("websocket鏈接失敗");
                Log.e("JWebSocketClientService",ex+"");

            }
        };
        connect();
    }

    /**
     * 鏈接websocket
     */
    private void connect() {
        new Thread() {
            @Override
            public void run() {
                try {
                    //connectBlocking多出一個等待操做,會先鏈接再發送,不然未鏈接發送會報錯
                    client.connectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }

    /**
     * 發送消息
     *
     * @param msg
     */
    public void sendMsg(String msg) {
        if (null != client) {
            Log.e("JWebSocketClientService", "發送的消息:" + msg);
            client.send(msg);
        }
    }


    /**
     * 斷開鏈接
     */
    private void closeConnect() {
        try {
            if (null != client) {
                client.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            client = null;
        }
    }


//    -----------------------------------消息通知--------------------------------------------------------

    /**
     * 檢查鎖屏狀態,若是鎖屏先點亮屏幕
     *
     * @param content
     */
    private void checkLockAndShowNotification(String content) {
        //管理鎖屏的一個服務
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        if (km.inKeyguardRestrictedInputMode()) {//鎖屏
            //獲取電源管理器對象
            PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
            if (!pm.isScreenOn()) {
                @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                        PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright");
                wl.acquire();  //點亮屏幕
                wl.release();  //任務結束後釋放
            }
            sendNotification(content);
        } else {
            sendNotification(content);
        }
    }

    /**
     * 發送通知
     *
     * @param content
     */
    private void sendNotification(String content) {
        Intent intent = new Intent();
        intent.setClass(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                // 設置該通知優先級
                .setPriority(Notification.PRIORITY_MAX)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle("服務器")
                .setContentText(content)
                .setVisibility(VISIBILITY_PUBLIC)
                .setWhen(System.currentTimeMillis())
                // 向通知添加聲音、閃燈和振動效果
                .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND)
                .setContentIntent(pendingIntent)
                .build();
        notifyManager.notify(1, notification);//id要保證惟一
    }


    //    -------------------------------------websocket心跳檢測------------------------------------------------
    private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒進行一次對長鏈接的心跳檢測
    private Handler mHandler = new Handler();
    private Runnable heartBeatRunnable = new Runnable() {
        @Override
        public void run() {

            if (client != null) {
                if (client.isClosed()) {
                    reconnectWs();
                }else if(client.isOpen()){
                    Log.e("JWebSocketClientService", "心跳包檢測websocket鏈接狀態");
                }

            } else {
                //若是client已爲空,從新初始化鏈接
                client = null;
                initSocketClient();
            }
            //每隔必定的時間,對長鏈接進行一次心跳檢測
            mHandler.postDelayed(this, HEART_BEAT_RATE);
        }
    };

    /**
     * 開啓重連
     */
    private void reconnectWs() {
        mHandler.removeCallbacks(heartBeatRunnable);
        new Thread() {
            @Override
            public void run() {
                try {
                    Log.e("JWebSocketClientService", "開啓重連");
                    client.reconnectBlocking();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}
複製代碼

(3)WebSocketUtil服務器

public class WebSocketUtil {
    public static final String ws = "ws://192.168.43.14:8080";//websocket測試地址
    public static void showToast(Context ctx, String msg) {
        Toast.makeText(ctx, msg, Toast.LENGTH_LONG).show();
    }
}複製代碼

三、在androidManifest理註冊servicewebsocket

<service
    android:name=".util.JWebSocketClientService"
    android:enabled="true"
    android:exported="true" />
<service
    android:name=".util.JWebSocketClientService$GrayInnerService"
    android:enabled="true"
    android:exported="false"
    android:process=":gray" />複製代碼
相關文章
相關標籤/搜索