我读了很多关于它并尝试了很多东西,没有成功。但它看起来并不难,所以我想我错过了一件小事。
我有2节课,MainActivity
和asynch task
课
doInBackground
任务工作正常。
但是当它完成后,我想编程继续我的MainActivity
protected Integer doInBackground(Void... params) {
try {
Log.d("control", "ZipHelper.unzip() - File: " + _archive);
ZipFile zipfile = new ZipFile(_archive);
for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e
.hasMoreElements();) {
ZipEntry entry = (ZipEntry) e.nextElement();
unzipEntry(zipfile, entry, _outputDir);
}
} catch (Exception e) {
Log.d("control", "ZipHelper.unzip() - Error extracting file "
+ _archive + ": " + e);
setZipError(true);
}
return null;
}
protected void onPostExecute(Integer... result) {
//Here something like MainActivity.showPicture();
}
我知道我必须对onPostExecute
做点什么,但我不知道到底是什么
那么,比方说,我想在MainActivity
完成后asynch-task
中展示一个Toast?
答案 0 :(得分:3)
使用监听器界面。
示例:
监听器接口
public interface AsyncTaskListener
{
public void onTaskComplete();
}
ZipHelper类
public class ZipHelper extends AsyncTask<Void, Void, Integer>
{
private String filename;
private AsyncTaskListener listener;
private File file;
public ZipHelper(String filename, File file, AsyncTaskListener listener)
{
this.filename = filename;
this.file = file;
this.listener = listener;
}
@Override
protected void onPreExecute()
{
//stuff here
}
@override
protected Integer doInBackground(Void... params)
{
//Background stuff here
}
@Override
protected void onPostExecute(Integer... result)
{
listener.onTaskComplete();
}
}
<强> MainActivity 强>
public class MainActivity implements AsyncTaskListener
{
public void onCreate(Bundle savedInstanceState)
{
super(savedInstanceState);
setContentView(R.layout.main_activity);
//Your stuff
new ZipHelper(zip[0].mZipFileName, file, MainActivity.this).execute();
}
public void onTaskComplete()
{
//AsyncTask post stuff
}
}
答案 1 :(得分:0)
如果不在MainActivity
中调用某种方法,则无法在MainActivity
中的某个位置开始。 AsyncTask
的要点是允许您的来电Activity
继续前进,而不是暂停UI
。您可以做的是将context
传递到AsyncTask
并在Toast
onPostExecute()
public class MyTask extends AsyncTask<Void, Void ,Void> { // use whatever params you need here
private Context context;
public MyTask(Context c) {
context = c;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, "You did it!". Toast.LENGTH_SHORT).show();
}
通过传递Context
Mytask task = new MyTask(this); //or MyActivity.this depending on where you are
task.execute(); // pass params if you need
我建议Activity context
Application context
代替Toast