Java 使用循环的异步任务示例

Java 使用循环的异步任务示例,java,android,Java,Android,我正在实现一个AsyncTask示例,并从这里的示例开始 然而,我想做一个改变。 在我的GUI中,我想放置一个文本框,用户可以在其中键入内容,并且每隔10秒,该名称就会出现在标签上 这样,如果用户输入了新值,它将显示在标签上,而不是现在显示的静态文本“已执行” 我的密码是贝娄 XML MainActivity.java import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; imp

我正在实现一个AsyncTask示例,并从这里的示例开始

然而,我想做一个改变。 在我的GUI中,我想放置一个文本框,用户可以在其中键入内容,并且每隔10秒,该名称就会出现在标签上

这样,如果用户输入了新值,它将显示在标签上,而不是现在显示的静态文本“已执行”

我的密码是贝娄

XML


MainActivity.java

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener {

    Button btn;
    EditText textInput;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button1);
        textInput = findViewById(R.id.textInput);
        // because we implement OnClickListener we only have to pass "this"
        // (much easier)
        btn.setOnClickListener(this);
    }

    public void onClick(View view) {
        // detect the view that was "clicked"
        switch (view.getId()) {
            case R.id.button1:
                new LongOperation().execute("");
                break;
        }
    }

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

        String input;

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                    input = textInput.getText().toString();
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText(input); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(Void... values) {}
    }
}
导入android.app.Activity;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
公共类MainActivity扩展活动实现View.OnClickListener{
按钮btn;
编辑文本输入;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(按钮)findViewById(R.id.button1);
textInput=findViewById(R.id.textInput);
//因为我们实现了OnClickListener,所以我们只需要传递“this”
//(容易多了)
btn.setOnClickListener(此);
}
公共void onClick(视图){
//检测“单击”的视图
开关(view.getId()){
案例R.id.button1:
新建LongOperation()。执行(“”);
打破
}
}
私有类LongOperation扩展了异步任务{
字符串输入;
@凌驾
受保护的字符串doInBackground(字符串…参数){
对于(int i=0;i<5;i++){
试一试{
睡眠(1000);
input=textInput.getText().toString();
}捕捉(中断异常e){
Thread.interrupted();
}
}
返回“已执行”;
}
@凌驾
受保护的void onPostExecute(字符串结果){
TextView txt=(TextView)findViewById(R.id.output);
txt.setText(输入);//txt.setText(结果);
//可能需要更改传递的返回字符串的“已执行”
//进入onPostExecute(),但这取决于您
}
@凌驾
受保护的void onPreExecute(){}
@凌驾
受保护的void onProgressUpdate(void…值){}
}
}
我将把代码放在哪里听?我想更改标签,每10秒检查一次(例如)文本框中是否有更改

编辑

根据答案,我可以这样离开无限循环吗?如果需要,如何停止此任务

private class LongOperation extends AsyncTask<String, String, String> {

    String input;

    @Override
    protected String doInBackground(String... params) {
        while (true)
            try {
                Thread.sleep(1000);
                input = textInput.getText().toString();
                publishProgress(input);

            } catch (InterruptedException e) {
                Thread.interrupted();
                return "Executed";
            }
    }

    @Override
    protected void onPostExecute(String result) {

    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(String... values) {
        TextView txt = (TextView) findViewById(R.id.output);
        txt.setText(values[0]);
        // update the UI with Data received from publishprogress
    }
}
私有类LongOperation扩展了异步任务{
字符串输入;
@凌驾
受保护的字符串doInBackground(字符串…参数){
while(true)
试一试{
睡眠(1000);
input=textInput.getText().toString();
出版进度(输入);
}捕捉(中断异常e){
Thread.interrupted();
返回“已执行”;
}
}
@凌驾
受保护的void onPostExecute(字符串结果){
}
@凌驾
受保护的void onPreExecute(){}
@凌驾
受保护的void onProgressUpdate(字符串…值){
TextView txt=(TextView)findViewById(R.id.output);
txt.setText(值[0]);
//使用从publishprogress接收的数据更新UI
}
}

您可以使用
PublishProgress
从后台线程更新UI

Void
更改为
String
以在
progressUpdate

private class LongOperation extends AsyncTask<String, String, String> {
//                                                    ^^^^^^
        String input;

        @Override
        protected String doInBackground(String... params) {
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                    input = textInput.getText().toString();
                    publishProgress(input);
                   //^^^^^^^^^ pass the data to update UI
                } catch (InterruptedException e) {
                    Thread.interrupted();
                }
            }
            return "Executed";
        }

        @Override
        protected void onPostExecute(String result) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText(input); // txt.setText(result);
            // might want to change "executed" for the returned string passed
            // into onPostExecute() but that is upto you
        }

        @Override
        protected void onPreExecute() {}

        @Override
        protected void onProgressUpdate(String... values) {
            TextView txt = (TextView) findViewById(R.id.output);
            txt.setText(values[0]);
            // update the UI with Data received from publishprogress
        }
    }
要取消任务,请先存储引用

AsynchTask task = new LongOperation().execute("");
task.cancel(true);

这两个答案是一致的,但你有更多的细节,哪些参数应该改变,我没有找到第一个答案。谢谢你们两位。要让我接受答案,只要确认我是否将其放入
中即可,而(true)
是保持无休止运行的最佳方式。如果需要,如何停止该过程?我将编辑问题,将代码放入循环。@JulianoRodrigoLamb检查更新,如果您将鼠标悬停在用户名上方的文本上说
answered…
,您可以检查准确时间,并尽量避免修改问题,因为原始问题已得到回答,尽管我不介意,但可能是其他问题。亲爱的,我不知道该怎么办。。我回答了一半。正如我在原文中所说,我需要在我的应用程序运行时始终执行此操作。在我的航路点中,可以使用循环
来解决此问题,而(true)
,因此,为了确认,我需要修改我的问题。不管怎样,我可以继续。谢谢你,帕夫尼特_Singh@JulianoRodrigoLamb一点问题也没有,我只是说你可以在你的问题中一次发布你所有的疑问,我很乐意帮忙。不需要道歉。。。快乐编码!虽然你也可以用
while(!isCancelled()){ // run as long as task is not cancelled

}
AsynchTask task = new LongOperation().execute("");
task.cancel(true);