我有一个 Activity 和一个异步任务。我想要异步任务中的进度结果到 Activity TextView 和 Activity TextView 中的最终结果。我停留在最后一点,即如何从 onProgressUpdate()
和 onPostExecute()
发送结果。帮我解决这个问题
MainActivity.java
public class MainActivity extends Activity {
TextView tv;
Button b1;
AsyncTask<Integer, Integer, Integer> ta;
private static String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.viewer);
b1 = (Button) findViewById(R.id.clicker);
tv.setText("2");
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int val = Integer.parseInt(tv.getText().toString());
ta = new TestAsync(getApplicationContext()).execute(val);
}
});
}
public void callOnEnd() {
try {
Log.d(TAG, "TestAsync " + ta.get() + " status " + ta.getStatus());
} catch(Exception e) {
Log.d(TAG, "TestAsync Exception " + e.toString());
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
TestAsync.java
public class TestAsync extends AsyncTask<Integer, Integer, Integer>{
Context context;
private static String TAG = "TestAsync";
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
public TestAsync(Context ctx) {
this.context = ctx;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
Log.d(TAG, TAG + "Reached AsyncTask");
}
@Override
protected Integer doInBackground(Integer... params) {
Log.d(TAG, TAG + "doInBackground");
int val = params[0], i, res;
for(i=0; i<100; i++) {
res = i * val;
publishProgress(res);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
Log.d(TAG, TAG + " onProgressUpdate " + values[0]);
}
@Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
Log.d(TAG, TAG + "onPostExecute " + result);
}
}
最佳答案
有两种可能:
将
AsyncTask
作为内部类实现:
您将能够从onProgressUpdate()
或onPostUpdate()
中访问MainActivity.this
。你可以调用这样的东西。@Override protected void onPostExecute(Integer result) { MainActivity.this.tv.setText("my result is: " + result); }
您可以在传递给
AsyncTask
的MainActivity
中创建某种接口(interface),以便从这些方法中调用它。public class MainActivity extends Activity { // all your code public void onResult(Integer result) { tv.setText("my result is: " + result); } }
在你的
AsyncTask
中:@Override protected void onPostExecute(Integer result) { ((MainActivity) context).onResult(result); }
您需要使用
MainActivity.this
而不是getApplicationContext()
创建TestAsync()
。否则,转换将失败。适当的
界面
会更好,但您明白了。
关于java - 如何从 onProgressUpdate 和 onPostExecute 获得响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22087861/