我有一個活動和一個asynctask。我希望將異步任務中的進度結果顯示在活動文本視圖中,並將最終結果顯示在活動文本視圖中。我最終停留在如何發送來自onProgressUpdate()
和onPostExecute()
的結果。幫我解決這個問題如何獲得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);
}
}
兩者都在2個diff類文件中。所以我應該如何嘗試訪問來自asynctask onPostExecute() – Venkat
的textView請參閱我的第二個選項:在'MainActivity'中創建一個方法,並從'AsyncTask'中調用它。 – flx
對不起,我剛剛在答案中找到了一個副本+過去的錯誤。第二次修復它。 – flx