Android - 使用okhttp websocket的NetworkOnMainThreadException

时间:2016-09-14 00:57:40

标签: android websocket okhttp

Android okhttp Websockets存在线程问题。我正在做一个聊天应用程序,我需要使用websocket在我们的服务器上编写和读取。

我在其他帖子中读到,使用Okhttp,我应该使用StrictMode.ThreadPolicy.Builder()。permitAll()因为它有一些问题等我添加了它。

但是当我尝试sendMessage时,我一直收到此错误:

W / System.err:android.os.NetworkOnMainThreadException 09-13 17:13:32.198 22766-22766 / com.microsoft.translator

请注意,我在另一个线程上发送Message,而不是在主线程上发送。

这是我的代码。感谢任何帮助。

创建websocket:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_chat);

   StrictMode.ThreadPolicy policy = new   StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    // lot other init stuff 
    createWebSocket();
}

private void createWebSocket() {
    okHttpClient = new OkHttpClient();
    Request request = new Request.Builder()
            .url(WSS_URL + token)
            .build();
    webSocketCall = WebSocketCall.create(okHttpClient, request);
    webSocketCall.enqueue(this);
}

@Override
public void onOpen(WebSocket webSocket, Response response) {
    try {
        Log.d(TAG, "onOpen: " + response.message());
        String message = createJsonMessage("Hello");
        byte[] messageBytes = message.getBytes();
        showToastOnUIThread("OnOpen sending message");

        webSocket.sendMessage(WebSocket.PayloadType.TEXT, new Buffer().write(messageBytes));
        this.webSocket = webSocket;
        //startRepeatingTask();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

    private void sendMessage(final String msgString) {

    Runnable postMessageThread = new Runnable() {
        @Override
        public void run() {
            String message = createJsonMessage(msgString);
            byte[] messageBytes = message.getBytes();

            try {
                if (webSocket != null) {
                    try {
                        webSocket.sendMessage(WebSocket.PayloadType.TEXT, new Buffer().write(messageBytes));
                    } catch (IOException e) {
                        e.printStackTrace();
                        Toast.makeText(ChatActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        Toast.makeText(ChatActivity.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    postMessageThread.run();
}

2 个答案:

答案 0 :(得分:1)

我认为这段代码是一个简单的示例。如果您不使用令牌进行身份验证,则可以删除addHeader。

OkHttpClient client = new OkHttpClient();

RequestBody requestBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("your_name_input", "your_value")
        .build();

Request request = new Request.Builder()
        .url("your_url")
        .post(requestBody)
        .addHeader("name_your_token", "your_token")
        .build();

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        e.printStackTrace();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        final String yourResponse = response.body().string();
        if(response.isSuccessful()){

            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "Ok: "+yourResponse,Toast.LENGTH_SHORT).show();
                }
            });
        }else{
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "Ok: "+yourResponse,Toast.LENGTH_SHORT).show();
                }
            });
        }


    }
});

您还可以在清单中添加权限

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

答案 1 :(得分:0)

我认为你的代码应该是这样的:

new Thread(new Runnable() {
        public void run() {
            // call send message here
        }
    }).start();

或者您可以使用Asyntask