好的,您正在尝试通过另一个线程访问GUI。基本上,这不是一个好习惯。
AsyncTask在
doInBackground()另一个线程内部执行所有 *** 作,该线程无法访问您的视图所在的GUI。
preExecute()并
postExecute()在此新线程发生繁重之前和之后为您提供访问GUI的权限,甚至可以将long *** 作的结果传递给
postExecute(),然后显示任何处理结果。
请在以后更新TextView的地方查看这些行:
TextView txt = findViewById(R.id.output);txt.setText("Executed");
把它们放进去
onPostExecute()。
doInBackground完成后,您将看到更新的TextView文本。
我注意到您的onClick侦听器不会检查是否已选择哪个视图。我发现最简单的方法是通过switch语句。我在下面编辑了一个完整的课程,其中包含所有建议,以免造成混淆。
import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.provider.Settings.System;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.view.View.OnClickListener;public class AsyncTaskActivity extends Activity implements onClickListener { Button btn; AsyncTask<?, ?, ?> runningTask; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); btn = findViewById(R.id.button1); // Because we implement OnClickListener, we only // have to pass "this" (much easier) btn.setonClickListener(this); } @Override public void onClick(View view) { // Detect the view that was "clicked" switch (view.getId()) { case R.id.button1: if (runningTask != null) runningTask.cancel(true); runningTask = new LongOperation(); runningTask.execute(); break; } } @Override protected void onDestroy() { super.onDestroy(); // Cancel running task(s) to avoid memory leaks if (runningTask != null) runningTask.cancel(true); } private final class LongOperation extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { for (int i = 0; i < 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { // We were cancelled; stop sleeping! } } return "Executed"; } @Override protected void onPostExecute(String result) { TextView txt = (TextView) findViewById(R.id.output); txt.setText("Executed"); // txt.setText(result); // You might want to change "executed" for the returned string // passed into onPostExecute(), but that is up to you } }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)