1

我读了很多关于它并尝试了很多东西,但没有成功。但这似乎并不难,所以我想我错过了一些东西。

我有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后显示一个 Toast asynch-task

4

2 回答 2

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();
    }
}

主要活动

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
    }
}
于 2013-05-06T14:32:36.967 回答
0

如果不调用您的某个方法,您MainActivity将无法从MainActivity. 的重点AsyncTask是让您的呼叫Activity继续进行而不是阻止UI. 您可以做的是将 a 传递context给您的并AsyncTask显示ToastonPostExecute()

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 contextforToast

于 2013-05-06T14:30:14.610 回答