如何加快使用http客户端的按钮的响应时间

时间:2014-11-30 16:06:43

标签: android arduino

我目前正在开发一个关于Android程序的项目,该程序可以控制带有以太网屏蔽的arduino,其主要目标是打开/关闭家用设备。 android程序定义了根据设备当前状态而变化的按钮。该项目已基本完成,但唯一的问题是某些按钮在按下时的响应时间会延迟但有些按钮不会。这个项目非常重要,所以请帮助我们。

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

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

    kitchenLight = (ToggleButton) findViewById(R.id.kitchenLight);
    kitchenLight.setOnClickListener(this);
    livingLight = (ToggleButton) findViewById(R.id.livingLight);
    livingLight.setOnClickListener(this);
    garageLight = (ToggleButton) findViewById(R.id.garageLight);
    garageLight.setOnClickListener(this);
    diningLight = (ToggleButton) findViewById(R.id.diningLight);
    diningLight.setOnClickListener(this);
}

public void commandArduino(String url) {
    try {
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.execute(new HttpGet(url));

    } catch (Exception e) {

    }
}


@Override
public void onClick(View v) {

    if (kitchenLight.isChecked()) {
        commandArduino("http://192.168.1.102/?lighton1");
    } else {
        commandArduino("http://192.168.1.102/?lightoff1");
    }

    if (livingLight.isChecked()) {
        commandArduino("http://192.168.1.102/?lighton2");
    } else {
        commandArduino("http://192.168.1.102/?lightoff2");
    }

    if (garageLight.isChecked()) {
        commandArduino("http://192.168.1.102/?lighton3");
    } else {
        commandArduino("http://192.168.1.102/?lightoff3");
    }

    if (diningLight.isChecked()) {
        commandArduino("http://192.168.1.102/?lighton4");
    } else {
        commandArduino("http://192.168.1.102/?lightoff4");
    }
}

1 个答案:

答案 0 :(得分:0)

这是一个问题,因为您在应用程序的UI线程上发出HTTP请求。通常,您不希望在UI线程上执行任何同步/阻塞IO,因为它会使您的应用程序无响应并且可以触发可怕的“应用程序无响应”对话框。

Android以AsyncTask类的形式为此问题提供了一个简单的解决方案。在你的情况下,你甚至不需要担心params或结果,因为看起来你可以解决火灾并忘记HTTP请求,你可以简单地将HttpGet实例传递给{{1构造函数。

为了帮助您入门,您可以像这样定义AysncTask的子类:

AsycnTask

然后,您可以使用以下内容替换public static class CommandArduino extends AsyncTask<Void, Void, Void> { private HttpUriRequest mRequest; public CommandArduino( HttpUriRequest request ){ mRequest = request; } protected Void doInBackground( Void... ignore ){ new DefaultHttpClient().execute( mRequest ); return null; } } 方法:

commandArduino

关于这个例子需要注意的一件事是使用Void类来表示我们不关心参数,进度或结果。通常情况下,您可以将这些类型参数设置为new CommandArduino(new HttpGet(url)).execute(); ,以便传入<URL, Integer, Integer>,使用URL显示进度,并将HTTP状态代码作为{ {1}}(或沿着这些方向的东西)。