从Asynctask返回到MainActivity

时间:2013-05-06 14:26:34

标签: java android android-asynctask

我读了很多关于它并尝试了很多东西,没有成功。但它看起来并不难,所以我想我错过了一件小事。

我有2节课,MainActivityasynch taskdoInBackground任务工作正常。 但是当它完成后,我想编程继续我的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?

2 个答案:

答案 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