簡體   English   中英

使用 OkHttp3 WebSocket 和 Retrofit 連續跟蹤 android 設備位置

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

我有以下 java 代碼,我想在 android 應用程序中使用它來查詢 api 以獲取持續的 lat/lng 變化,以跟蹤正在運行客戶端的設備的應用程序。 我相信我嘗試使用的 WebSocketCall 方法已被棄用。 據我所知,我嘗試使用 webSocket 調用創建 retrofit 客戶端並將來自 WebSocketListner 的數據排入 ZBD279364F96CA5CBCA79389D54ZBZ 客戶端的方式存在問題。 我研究了幾個 WebSocketListener 示例,並且作為一個總 n00b,我無法弄清楚代碼。 我的想法是通過 WebSocket 保持與 api 的連接打開,並使用 retrofit 處理數據響應。 任何幫助將不勝感激。

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;
            }
        });
    }

所以因為我是一個完全的n00b,所以花了一些時間和很多問題來解決這個問題。 也許它會在未來幫助別人。

 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