WebsocketService.java 5.56 KB
package com.huaheng.mobilewms.websocket;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.huaheng.mobilewms.R;
import com.huaheng.mobilewms.WMSApplication;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import io.reactivex.schedulers.Schedulers;
import rx.android.schedulers.AndroidSchedulers;
import ua.naiksoftware.stomp.Stomp;
import ua.naiksoftware.stomp.StompClient;
import ua.naiksoftware.stomp.dto.StompCommand;
import ua.naiksoftware.stomp.dto.StompHeader;
import ua.naiksoftware.stomp.dto.StompMessage;

public class WebsocketService extends Service {
    private StompClient mStompClient;
    private int notify_id = 0;
    private String TAG = "WebsocketService";

    public WebsocketService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("WebsocketService", "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        if(mStompClient == null || !mStompClient.isConnected()) {
            createStompClient(WebsocketConstants.getUri());
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        mStompClient.topic(WebsocketConstants.SUBSCRIBE_TOPIC_MESSAGE).unsubscribeOn(Schedulers.io());
        mStompClient.topic(WebsocketConstants.SUBSCRIBE_USER_TOPIC_MESSAGE).unsubscribeOn(Schedulers.io());
        mStompClient.disconnect();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @SuppressLint("CheckResult")
    private void createStompClient(String uri) {
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Cookie", WMSApplication.getOkhttpCookie());
        mStompClient = Stomp.over(Stomp.ConnectionProvider.OKHTTP, uri, headers);
        mStompClient.connect();
        mStompClient.withClientHeartbeat(WebsocketConstants.HEART_BEAT_CLIENT).withServerHeartbeat(WebsocketConstants.HEART_BEAT_SERVER);
        mStompClient.lifecycle().subscribe(lifecycleEvent -> {
            switch (lifecycleEvent.getType()) {

                case OPENED:
                    Log.d(TAG, "Stomp connection opened");
                    mStompClient.topic(WebsocketConstants.SUBSCRIBE_TOPIC_MESSAGE)
                            .subscribeOn(Schedulers.io())
//                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(topicMessage -> {
                                showNotification("WMS广播消息", topicMessage.getPayload().toString());
//                                showShort(topicMessage.getPayload());
                            });
                    mStompClient.topic(WebsocketConstants.SUBSCRIBE_USER_TOPIC_MESSAGE)
                            .subscribeOn(Schedulers.io())
//                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(topicMessage -> {
//                                showShort(topicMessage.getPayload());
                                showNotification("收货通知", topicMessage.getPayload().toString());
                                confirmMessage(topicMessage);
                            });
                    break;

                case ERROR:
                    Log.e(TAG, "Error", lifecycleEvent.getException());
//                    startActivity(LoginActivity.class);
                    break;

                case CLOSED:
                    Log.d(TAG, "Stomp connection closed");
                    break;
            }
        });

    }

    /**
     * 回复收到消息
     *
     * @param msg
     */
    private void confirmMessage(StompMessage msg) {
        for (StompHeader header : msg.getStompHeaders()) {
            if (header.getKey().equals(WebsocketConstants.HEADER_MEG_ID)) {
                String msg_id = header.getValue();
                List<StompHeader> headers = new ArrayList<>();
                headers.add(new StompHeader(WebsocketConstants.HEADER_MEG_ID, msg_id));
                headers.add(new StompHeader(StompHeader.DESTINATION, WebsocketConstants.UP_CONFIRM_MESSAGE_DEST));
                mStompClient.send(new StompMessage(StompCommand.SEND, headers, null)).subscribe();
            }
        }
    }

    public void showShort(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    private void showNotification(String title, String payload){
        Message msg = null;
        try{
            msg = new Gson().fromJson(payload, Message.class);
        }catch (Exception e){
            msg = new Message();
            msg.setTitle("WMS通知");
            msg.setContent(payload);
        }
        NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Notification notification = new NotificationCompat.Builder(this, "default")
                .setContentTitle(msg.getTitle())
                .setContentText(msg.getContent())
                .setWhen(msg.getWhen())
                .setSmallIcon(R.mipmap.menu2_icon_pljh)
                .build();
        manager.notify(notify_id++, notification);
    }
}