简体   繁体   English

使用 OkHttp3 WebSocket 和 Retrofit 连续跟踪 android 设备位置

[英]Using OkHttp3 WebSocket with Retrofit to continuously track an android devices location

I have the following java code that I'd like to use in an android app to query an api for continuous lat/lng changes of a device that is running a client app, I want to track the device.我有以下 java 代码,我想在 android 应用程序中使用它来查询 api 以获取持续的 lat/lng 变化,以跟踪正在运行客户端的设备的应用程序。 I believe the WebSocketCall method I'm attempting to use is deprecated.我相信我尝试使用的 WebSocketCall 方法已被弃用。 From what I can tell, there's a problem with how I'm trying to use the webSocket call to create the retrofit client and enqueue the data from the WebSocketListner into retrofit.据我所知,我尝试使用 webSocket 调用创建 retrofit 客户端并将来自 WebSocketListner 的数据排入 ZBD279364F96CA5CBCA79389D54ZBZ 客户端的方式存在问题。 I've researched several WebSocketListener examples and being a total n00b, I haven't been able to figure out the code.我研究了几个 WebSocketListener 示例,并且作为一个总 n00b,我无法弄清楚代码。 My idea is to keep the connection open to the api via WebSocket and process the data response using retrofit.我的想法是通过 WebSocket 保持与 api 的连接打开,并使用 retrofit 处理数据响应。 Any assistance would be greatly appreciated.任何帮助将不胜感激。

private WebSocketCall webSocket;

    private void createWebSocket() {
        final MainApplication application = (MainApplication) getActivity().getApplication();
        application.getServiceAsync(new MainApplication.GetServiceCallback() {
            @Override
            public void onServiceReady(final OkHttpClient client, final Retrofit retrofit, WebService service) {
                User user = application.getUser();
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                        new LatLng(user.getLatitude(), user.getLongitude()), user.getZoom()));
                service.getDevices().enqueue(new WebServiceCallback<List<Device>>(getContext()) {
                    @Override
                    public void onSuccess(retrofit2.Response<List<Device>> response) {
                        for (Device device : response.body()) {
                            if (device != null) {
                                devices.put(device.getId(), device);
                            }
                        }

                        Request request = new Request.Builder().url(retrofit.baseUrl().url().toString() + "api/socket").build();
                        webSocket = WebSocketCall.create(client, request);
                        webSocket.enqueue(new WebSocketListener() {
                            @Override
                            public void onOpen(WebSocket webSocket, Response response) {
                            }

                            @Override
                            public void onFailure(IOException e, Response response) {
                                reconnectWebSocket();
                            }

                            @Override
                            public void onMessage(ResponseBody message) throws IOException {
                                final String data = message.string();
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            handleMessage(data);
                                        } catch (IOException e) {
                                            Log.w(MainFragment.class.getSimpleName(), e);
                                        }
                                    }
                                });
                            }

                            @Override
                            public void onClose(int code, String reason) {
                                reconnectWebSocket();
                            }
                        });
                    }
                });
            }

            @Override
            public boolean onFailure() {
                return false;
            }
        });
    }

So because I'm a total n00b it took some time and a lot of questions to figure this out.所以因为我是一个完全的n00b,所以花了一些时间和很多问题来解决这个问题。 Maybe it'll help someone else in the future.也许它会在未来帮助别人。

 private WebSocket webSocket;

private void createWebSocket() {
        final MainApplication application = (MainApplication) getActivity().getApplication();
        application.getServiceAsync(new MainApplication.GetServiceCallback() {
            @Override
            public void onServiceReady(final OkHttpClient client, final Retrofit retrofit, WebService service) {
                User user = application.getUser();
                map.moveCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(user.getLatitude(), user.getLongitude()), user.getZoom()));

                service.getDevices().enqueue(new WebServiceCallback<List<Device>>(getContext()) {
                    @Override
                    public void onSuccess(retrofit2.Response<List<Device>> response) {
                        for (Device device : response.body()) {
                            if (device != null) {
                                devices.put(device.getId(), device);
                            }
                        }

                        Request request = new Request.Builder().url(retrofit.baseUrl().url().toString() + "api/socket").build();
                        Log.e("WebSockets", "Headers: " + request.headers().toString());
                        WebSocketListener webSocketListener = new WebSocketListener() {
                            private static final int NORMAL_CLOSURE_STATUS = 1000;
                            @Override
                            public void onOpen(WebSocket webSocket, Response response) {
                                webSocket.send("{Auth-Token:secret-api-token-here}");
                                Log.e("WebSockets", "Connection accepted!");
                            }

                            @Override
                            public void onFailure(@NotNull WebSocket webSocket, @NotNull Throwable t, @Nullable Response response) {
                                reconnectWebSocket();
                            }

                            @Override
                            public void onMessage(@NotNull WebSocket webSocket, @NotNull String text) {
                                final String data = text;
                                Log.e("WebSockets", "Receiving : " + text);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            handleMessage(data);
                                        } catch (IOException e) {
                                            Log.w(MainFragment.class.getSimpleName(), e);
                                        }
                                    }
                                });
                            }
                            @Override
                            public void onMessage(WebSocket webSocket, ByteString bytes) {
                                Log.e("WebSockets", "Receiving bytes : " + bytes.hex());
                            }

                            @Override
                            public void onClosing(WebSocket webSocket, int code, String reason) {
                                webSocket.close(NORMAL_CLOSURE_STATUS, null);
                                Log.e("WebSockets", "Closing : " + code + " / " + reason);
                            }

                            @Override
                            public void onClosed(@NotNull WebSocket webSocket, int code, @NotNull String reason) {
                                reconnectWebSocket();
                            }
                        };

                        webSocket = client.newWebSocket(request, webSocketListener);
                    }
                });
            }

            @Override
            public boolean onFailure() {
                return false;
            }
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM