返回从非同步任务以MainActivity [英] Returning from Asynch Task to MainActivity
问题描述
我读了很多关于它,并试图很多东西,而无需更迭。但它似乎并不难可言,所以我想我缺少了一点东西。
I read a lot about it and tried many things, without having succes. But it doesn't seem hard at all, so I guess I am missing a little thing.
我得到了2班, MainActivity
和非同步任务
类。结果
在 doInBackground
任务可以正常使用。
但是,当它完成,我想程序继续运行在某一点上我的 MainActivity
I got 2 classes, a MainActivity
and an asynch task
class.
the doInBackground
task is working perfectly.
But when it is done, I want to program to continue at a certain point in my 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
在非同步任务
做?
I know I must do something with onPostExecute
, but I don't know what exactly.
So let's say, I want to show a Toast in my MainActivity
after asynch-task
is done?
推荐答案
使用监听器接口。
示例:
Listener接口
Listener Interface
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
}
}
这篇关于返回从非同步任务以MainActivity的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!