热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从套接字输入流读取导致AndroidUI冻结-ReadingfromsocketinputstreamscausingandroidUItofreeze

Imtryingtowritethisprogramwhichupdatesitselfonthecurrentstatusofavariable.HowIint

I'm trying to write this program which updates itself on the current status of a variable. How I intended it to work is by having a timed task to constantly send the string "update" to the server. The server will recognize the string and will send the necessary values for the variable on the android device. However, I am facing some problems. The string "update" is sending without error but when the corresponding value from the server is sent back, the program does not seem to be able to read the reply. Here is the code:

我正在尝试编写这个程序,它自动更新变量的当前状态。我打算如何工作是通过定时任务不断向服务器发送字符串“update”。服务器将识别该字符串,并将在Android设备上发送变量的必要值。但是,我遇到了一些问题。字符串“update”发送时没有错误,但是当发回服务器的相应值时,程序似乎无法读取回复。这是代码:

            //Open socket and initialize data streams
    try {
        socket = new Socket(serverIpAddress, applicationport);
        //in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //in = new DataInputStream(socket.getInputStream());
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                socket.getOutputStream())), true);
    } catch (UnknownHostException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
        ShowDialog("Login Error" + ex.getMessage());
    } catch (IOException ex) {
        // TODO Auto-generated catch block
        ex.printStackTrace();
        ShowDialog("Login Error" + ex.getMessage());
    }

    //Create new daemon timer
    updateData = new Timer(true);
    updateData.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            out.println("update");
            UpdateMethod();
            }//run
        }, 1000, 10000);//schedule the delays start/interval here



};

private void UpdateMethod() {
    //This method is called directly by the timer
    //and runs in the same thread as the timer.
    //It calls the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(Timer_Tick);
};//timermethod

private Runnable Timer_Tick = new Runnable() {
    public void run() {
        try {
            //in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //String getx1 = null;
            //getx1 = in.readLine();
            //if (getx1 != null) {
                //float updatex1 = Float.parseFloat(getx1);
                //get_x1 = getx1;
                //}
            in = new DataInputStream(socket.getInputStream());
            /*try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }*/
            x1display = (TextView) findViewById(R.id.x1display);
            x1display.setText(in.readUTF());

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
};

As you can see, I have tried experimenting with both DataInputStream and BufferedReader as well but to no avail.

正如您所看到的,我也尝试过使用DataInputStream和BufferedReader,但无济于事。

Edit: It seems that trying to read from the input stream is causing my UI to freeze up. I have no idea what is wrong as my code seems to be without errors..

编辑:似乎尝试从输入流中读取导致我的UI冻结。我不知道出了什么问题,因为我的代码似乎没有错误。

Any help or advice would be greatly appreciated!

任何帮助或建议将不胜感激!

Thank you!

2 个解决方案

#1


0  

The code looks fine to me. But its not working so looks like you need to chop it up.

代码看起来很好。但它没有工作所以看起来你需要把它砍掉。

  • Test if the socket stuff is working without the Timer. Make a socket connection and read its response without the Timer and UI code

    测试套接字是否在没有Timer的情况下工作。在没有Timer和UI代码的情况下建立套接字连接并读取其响应

  • If that works, introduce the Timer but not the UI code

    如果可行,请介绍Timer但不介绍UI代码

  • If that works, do the whole thing (which is failing now)

    如果有效,那就完成整个事情(现在失败了)

Somewhere in this test process you should be able to find the culprit

在这个测试过程的某个地方,你应该能找到罪魁祸首

#2


0  

As you have already said, reading blocks the thread. You shouldn't ever read something inside the UI thread! Furthermore, as I remember correctly, closing input before closing output does some nasty things. I would suggest closing the socket instead and putting the BufferedReader back in. This is how it should look like:

正如您已经说过的那样,读取阻塞线程。你不应该在UI线程中读到一些东西!此外,正如我记得的那样,在关闭输出之前关闭输入会产生一些令人讨厌的事情。我建议关闭套接字,然后重新放入BufferedReader。这就是它应该是这样的:

//Open socket and initialize data streams
try {
    socket = new Socket(serverIpAddress, applicationport);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
            socket.getOutputStream())), true);
} catch (UnknownHostException ex) {
    ex.printStackTrace();
    ShowDialog("Login Error" + ex.getMessage());
} catch (IOException ex) {
    ex.printStackTrace();
    ShowDialog("Login Error" + ex.getMessage());
}

//Create new daemon timer
updateData = new Timer(true);
updateData.scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        out.println("update");
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    x1display = (TextView) findViewById(R.id.x1display);
                    x1display.setText(in.readUTF());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        try {
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }}, 1000, 10000);//schedule the delays start/interval here

By the way, don't use printStackTrace(): Why is exception.printStackTrace() considered bad practice?

顺便说一句,不要使用printStackTrace():为什么exception.printStackTrace()被认为是不好的做法?


推荐阅读
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
  • 带添加按钮的GridView,item的删除事件
    先上图片效果;gridView无数据时显示添加按钮,有数据时,第一格显示添加按钮,后面显示数据:布局文件:addr_manage.xml<?xmlve ... [详细]
  • 本篇文章笔者在上海吃饭的时候突然想到的这段时间就有想写几篇关于返回系统的笔记,所以回家到之后就奋笔疾书的写出来发布了事先在网上找了很多方法,发现有 ... [详细]
  • 与.Net大师Jeffrey Richter面对面交流——TUP对话大师系列活动回顾(多图配详细文字)...
    与.Net大师JeffreyRichter面对面交流——TUP对话大师系列活动回顾(多图配文字)上周末很有幸参加了CSDN举行的TUP活动, ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了使用Java实现大数乘法的分治算法,包括输入数据的处理、普通大数乘法的结果和Karatsuba大数乘法的结果。通过改变long类型可以适应不同范围的大数乘法计算。 ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • JavaSE笔试题-接口、抽象类、多态等问题解答
    本文解答了JavaSE笔试题中关于接口、抽象类、多态等问题。包括Math类的取整数方法、接口是否可继承、抽象类是否可实现接口、抽象类是否可继承具体类、抽象类中是否可以有静态main方法等问题。同时介绍了面向对象的特征,以及Java中实现多态的机制。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 本文整理了Java面试中常见的问题及相关概念的解析,包括HashMap中为什么重写equals还要重写hashcode、map的分类和常见情况、final关键字的用法、Synchronized和lock的区别、volatile的介绍、Syncronized锁的作用、构造函数和构造函数重载的概念、方法覆盖和方法重载的区别、反射获取和设置对象私有字段的值的方法、通过反射创建对象的方式以及内部类的详解。 ... [详细]
  • 概述H.323是由ITU制定的通信控制协议,用于在分组交换网中提供多媒体业务。呼叫控制是其中的重要组成部分,它可用来建立点到点的媒体会话和多点间媒体会议 ... [详细]
author-avatar
辛博的调调最棒
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有