而插座进行读/写操作过于频繁应用程序无响应 [英] Application not responding while performing a read/write operation on socket too frequently

查看:262
本文介绍了而插座进行读/写操作过于频繁应用程序无响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我有一个用于读取状态12位的字节数组。写这阵之后我得到不同的按钮的状态。在此基础上的反应,我是我的按钮设置为ON | OFF。我这样做的任务repeatedly.if我设置间隔时间过少即100毫秒和pressing这些按钮过于频繁那么我的应用程序停止响应。

In my application i have byte array of 12 digit which is used to read the status. After writing this array i am getting the status of different buttons. Based on this response i am setting up my buttons to ON|OFF. i am doing this task repeatedly.if i set this interval time too less i.e 100ms and pressing those buttons too frequently then my application is stops to respond.

下面是code片段。

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

    fanDimmer1=(ToggleButton)findViewById(R.id.button_fan1);
    fanDimmer2=(ToggleButton)findViewById(R.id.button_fan2);
    dimmerLight1=(ToggleButton)findViewById(R.id.button_light1);
    dimmerLight2=(ToggleButton)findViewById(R.id.button_light2);


    fanDimmer1.setOnClickListener(this);
    fanDimmer2.setOnClickListener(this);
    dimmerLight1.setOnClickListener(this);
    dimmerLight2.setOnClickListener(this);

    if(ip.equals("") || port.equals(""))
    {
        new AlertDialog.Builder(MainActivity.this)
        .setTitle("Warning !")
        .setMessage("Please set IP and PORT first")
        .setIcon(android.R.drawable.ic_dialog_alert)
        .setNeutralButton("ok", null)
        .show();
    }
    else
    {
        new Thread(new Runnable() 
        {   
            @Override
            public void run()
            {
                Log.v(TAG, "openconnection");
                openConnection();
            }
        }).start();
        m_handler = new Handler();
        startRepeatingTask();

    }

}

public void openConnection()
{
    // TODO Auto-generated method stub
    try 
    {
        s = new Socket(ip, Integer.parseInt(port));
        i = s.getInputStream();
        iD = new DataInputStream(i);
        o = s.getOutputStream();
        oD = new DataOutputStream(o);
        Log.v(TAG, "openconnection 2");

    }
    catch (UnknownHostException e) {
        // TODO: handle exception
        Log.v("UnknowHostException :::::", "In Catch Block");
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO: handle exception
        Log.v("IOException :::::", "In Catch Block");
        e.printStackTrace();
    }
}

Runnable m_statusChecker = new Runnable() 
{
    @Override
    public void run() 
    {
        updateStatus();
        m_handler.postDelayed(m_statusChecker,100);
    }

    private void updateStatus() 
    {
        // TODO Auto-generated method stub
        Log.v("test", "1");
        try {
            byte[] data1 = new byte[1024], packet1 = 
                { 
                    (byte) 0x00,(byte) 0x00,(byte) 0x00, 
                    (byte) 0x00,(byte) 0x00,(byte) 0x06, 
                    (byte) 0x01,(byte) 0x01,(byte) 0x00,
                    (byte) 0x00,(byte) 0x00,(byte) 0x19
                };

            o.write(packet1);
            i.read(data1, 0, 1024);

            byte_to_hex = ConversionMethods.bytesToHex(data1).substring(18, 26);
            char[] arr = byte_to_hex.toCharArray();
            for (int i = 0; i < arr.length - 1; i += 2) 
            {
                char temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
            }

            swapped_result=new String(arr);
            result = ConversionMethods.hexStringToNBitBinary(swapped_result, 32);

            int counter = 0;
            for( int i=0; i<result.length(); i++ ) 
            {
                if( result.charAt(i) == '1' )
                {
                    counter++;        
                }  
            }
            status=Integer.toString(counter);
            txt_status.setText(status);
            Log.v(TAG, "status is ::"+status);


            char[] c=result.toCharArray();
            int count=0;
            for (int i=0;i<result.length();i++)
            {
                count++;
                char j=c[i];
                //Log.v(TAG, count+"::"+j);
                if(count==1)
                    toggleButton=dimmerLight1;
                else if(count==2)
                    toggleButton=fanDimmer2;
                else if(count==3)
                    toggleButton=fanDimmer1;
                else if(count==4)
                    Log.v(TAG, "Count 4 is 0");

                if(j=='1')
                    toggleButton.setChecked(true);
                else
                    toggleButton.setChecked(false); 
            }

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
};

void startRepeatingTask() {
    m_statusChecker.run();
}

void stopRepeatingTask() {
    m_handler.removeCallbacks(m_statusChecker);
}

和按钮点击我这样做:

@Override
public void onClick(View v) 
{

    if(v.equals(fanDimmer1))
    {
        if (fanDimmer1.isChecked()) 
        {
            Toast.makeText(MainActivity.this, "Fan 1 is ON", Toast.LENGTH_SHORT).show();
            setByteArray((byte) 0x01, (byte) 0xff);
        } else 
        {
            Toast.makeText(MainActivity.this, "Fan 1 is OFF", Toast.LENGTH_SHORT).show();
            setByteArray((byte) 0x01, (byte) 0x00);
        }
    }

}

这里是 setByteArray()方法
我有24个这种类型的按钮。

here is setByteArray() method i have 24 this type of buttons.

任何意见和建议,将AP preciated。结果
谢谢

Any advice and suggestion will be appreciated.
Thanks

推荐答案

您在呼唤 startRepeatingTask()从你的主线程:

You are calling startRepeatingTask() from your main thread:

void startRepeatingTask() {
   m_statusChecker.run();
}

这意味着你将statusChecker在主线程中运行了。

This means that your statusChecker will runs in the main thread too.


  • 做的第一件事就是更新updateStatus方法的code和使用 mHandler 后唯一的用户界面更新code到主UI线程

  • The first thing to do is to update the code of your updateStatus method and use mHandler to post ONLY ui-update code to the main UI-thread

接下来,您必须在另一个线程运行statusChecker

Next you have to run the statusChecker in another thread

要做到这一点,你有(至少)两个选项:

To do it, you have (at least) two options :


  1. [复杂的方式]执行自己的线程管理和写这样的事情在你的startRepeatingTask

  1. [The complex way] Do your own thread management and write something like this in your startRepeatingTask

无效startRepeatingTask(){
   新的Thread(m_statusChecker)。开始();
}

适应stop方法(即使用一个显示器,一个无限循环和睡眠)

adapt the stop method (i.e. use a monitor, an infinite loop and a sleep)

[聪明的办法]看看定时器 TimerTask的(和<一个href=\"http://stackoverflow.com/questions/2161750/android-controlling-a-task-with-timer-and-timertask\">this)从Android API和使用它们来实现你所需要的。

[The smart way] Take a look at Timer and TimerTask (and this) from the Android API and use them to implement what you need.

修改

专注于这个code:

for (int i=0;i<result.length();i++)
        {
            count++;
            char j=c[i];
            //Log.v(TAG, count+"::"+j);
            if(count==1)
                toggleButton=dimmerLight1;
            else if(count==2)
                toggleButton=fanDimmer2;
            else if(count==3)
                toggleButton=fanDimmer1;
            else if(count==4)
                Log.v(TAG, "Count 4 is 0");

            if(j=='1')
                toggleButton.setChecked(true);
            else
                toggleButton.setChecked(false); 
        }

这个循环的效果将是:

The effect of this loop will be:


  • 迭代0(如果有的话):dimmerLight1会被选中或取消选中

  • 迭代1(如果有的话):fanDimmer2会被选中或取消选中

  • 迭代2(如果有的话):fanDimmer1会被选中或取消选中

  • 迭代3(如果有的话):fanDimmer1会被选中或取消选中

  • 迭代4(如果有的话):fanDimmer1会被选中或取消选中

  • 迭代5(如果有的话):fanDimmer1会被选中或取消选中

  • ...(fanDimmer1将是检查或取消选中,直到循环结束)

我是pretty确保这个你不需要的东西。 (除非result.size()始终是3,但在任何其他情况:今年code会产生奇怪的事情)

I'm pretty sure this not what you need. (except if result.size() is always 3, but in any other situation: this code will produce weird things)

您可以做这样的事情:

//assuming buttons is a ToggleButton[32] populated with all your buttons in the correct order
for (int i=0;i<result.length();i++)
    {
        buttons[i].setChecked(c[i]=='1'); 
    }

这篇关于而插座进行读/写操作过于频繁应用程序无响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆