当我调用bufferedReader.readLine()时,我的Android应用程序正在冻结;

时间:2015-08-20 20:03:26

标签: java android bufferedreader wear-os channel-api

我为Android手机和Android Wear创建了一个新的Android Studio项目来测试ChannelApi。似乎一切都在我的项目中正常工作,除了在onChannelOpened方法内部我无法在不冻结应用程序的情况下从InputStream读取。

这是我从Wearable发送消息的方式(似乎有效):

Wearable.ChannelApi.openChannel(googleApiClient, node.getId(), channelIdentifier).setResultCallback(new ResultCallback<ChannelApi.OpenChannelResult>() {
    @Override
    public void onResult(ChannelApi.OpenChannelResult openChannelResult) {
        final Channel channel = openChannelResult.getChannel();
        channel.getOutputStream(googleApiClient).setResultCallback(new ResultCallback<Channel.GetOutputStreamResult>() {
        @Override
        public void onResult(final Channel.GetOutputStreamResult getOutputStreamResult) {
        final String message = "hello from your smartwatch";
        try {
            getOutputStreamResult.getOutputStream().write(message.getBytes());
            Log.d(TAG, "sendMessageToNode: onResult: onResult: Message sent: " + message);
        }
        // ...

日志打印:D/MainActivity﹕ sendMessageToNode: onResult: onResult: Message sent: hello from your smartwatch

在智能手机方面,我尝试按如下方式阅读信息:

@Override
public void onChannelOpened(final Channel channel) {
    channel.getInputStream(googleApiClient).setResultCallback(new ResultCallback<Channel.GetInputStreamResult>() {
        @Override
        public void onResult(Channel.GetInputStreamResult getInputStreamResult) {
            Log.d(TAG, "onChannelOpened: onResult");

            String message = "";
            InputStream inputStream = null;
            BufferedReader bufferedReader = null;
            try {
                inputStream = getInputStreamResult.getInputStream();
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String line = "";
                //while ((line = bufferedReader.readLine()) != null) {
                while (true) {
                    // Next line is freezing the app
                    line = bufferedReader.readLine();
                    Log.d(TAG, "onChannelOpened: onResult: line: " + line);
                    message += line + "\n";
                    if (line == null) break;
                }
                Log.d(TAG, "onChannelOpened: onResult: Received the following message: \" + message");
                // ...

日志打印:D/MainActivity﹕ onChannelOpened: onResult但是就是这样。

我启动了调试器,现在知道错误必须在这一行:line = bufferedReader.readLine();。但是没有抛出异常或其他任何东西。调试器甚至向我显示缓冲区具有正确的值:

Debugger shows right values

我正试图从你的智能手表&#34;发送#34;你好。但是,应用似乎冻结了。有谁知道为什么?

1 个答案:

答案 0 :(得分:1)

您需要在发送方关闭流,否则接收方将不知道是否有更多数据通过该频道传输。