如何在android中同时处理两个按钮事件

时间:2016-05-10 21:30:02

标签: android android-asynctask esp8266 nodemcu

我已经通过wifi开发了一个android应用程序到rc汽车。为此,我使用了esp8266 nodemcu wifi模块。在我的应用程序中有4个按钮,分别是前进,后退,右和左。我可以通过wifi连接这个模块,并为ex做一些基本的操作。向前移动,向后移动,向右转,向左转。以下是执行此操作的代码:

 @Override
public boolean onTouch(View v, MotionEvent event) {
    String action;

    if (v.getId() == moveForward.getId())
        action = "/forward/";

    else if (v.getId() == moveReverse.getId())
        action = "/reverse/";

    else if (v.getId() == moveRigth.getId())
        action = "/right/";

    else
        action = "/left/";

    String serverAddress = ipAddress.getText().toString() + ":" + "80" + action;

    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        HttpRequestTask requestTask = new HttpRequestTask(serverAddress);
        requestTask.execute("1");

    } else if (event.getAction() == MotionEvent.ACTION_UP) {
        HttpRequestTask requestTask = new HttpRequestTask(serverAddress);
        requestTask.execute("0");
    }
    return false;
}

 private class HttpRequestTask extends AsyncTask<String, Void, String> {

    private String serverAdress;
    private String serverResponse = "";

    public HttpRequestTask(String serverAdress) {
        this.serverAdress = serverAdress;
    }

    @Override
    protected String doInBackground(String... params) {

        String val = params[0];
        String url = "http://" + serverAdress + val;
        Log.e("url", url);

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet();
            getRequest.setURI(new URI(url));
            HttpResponse response = client.execute(getRequest);

            InputStream inputStream = null;
            inputStream = response.getEntity().getContent();
            BufferedReader bufferedReader =
                    new BufferedReader(new InputStreamReader(inputStream));

            serverResponse = bufferedReader.readLine();
            inputStream.close();

        } catch (URISyntaxException e) {
            e.printStackTrace();
            serverResponse = e.getMessage();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
            serverResponse = e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            serverResponse = e.getMessage();
        }

        return serverResponse;
    }

当用户向前按下时,也可以按下右键或左键,汽车前进右转或后退,同时向左转。但我怎么办不能在代码中同时处理按下两个按钮的事件。你能告诉我一个方法吗?

1 个答案:

答案 0 :(得分:0)

 if (v.getId() == moveForward.getId())
        action = "/forward/";

 if (v.getId() == moveReverse.getId())
        action = "/reverse/";

 if (v.getId() == moveRigth.getId())
        action = "/right/";

 if (v.getId() == moveLeft.getId())
        action = "/left/";

所以你可以处理所有的动作,你的旧代码只会测试一个条件