我应该在保持按钮操作中使用AsyncTask还是线程?

时间:2018-05-24 22:00:13

标签: android android-asynctask ontouchlistener ontouchevent

我有一个将数据写入套接字的AsyncTask,我不想做一个onTouch事件,该事件持有按钮直到发布。我实际上是用AsyncTask完成的,但应用程序在写入套接字后崩溃了。我应该使用线程,还是有更好的解决方案来解决这个问题?

编辑:我在logcat中收到消息“正在等待阻止GC Alloc”。

OnTouchListener代码:

buttonUp.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            while(true){
                if (event.getAction() == MotionEvent.ACTION_DOWN){
                    new moveForward().execute();
                } else if (event.getAction() == MotionEvent.ACTION_UP){
                    break;
                }
            }

            return false;
        }
    });

AsyncTask代码:

private class moveForward extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... voids) {
        try {
            MainActivity.client.write('u');

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

        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
    }
}

1 个答案:

答案 0 :(得分:0)

你永远不应该在主UI线程上运行无限循环。您可以在ACTION_DOWN中启动任务并在ACTION UP中结束它。你无休止地开始了多项任务。试试这段代码

    moveForward moveForward;
    buttonUp.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN){
                    moveForward = new moveForward();
                    moveForward.execute();
                } else if (event.getAction() == MotionEvent.ACTION_UP){
                    moveForward.cancel(true);
                }

            return false;
        }
    });


    private class moveForward extends AsyncTask<Void, Void, Void>{

    @Override
    protected Void doInBackground(Void... voids) {
        while(!isCancelled()) {
            try {
                MainActivity.client.write('u');

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

            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
         }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
    }
}