2013-05-06 92 views
1

我读了很多关于它并尝试了很多东西,没有成功。但这似乎并不困难,所以我想我错过了一件小事。从异步任务返回到MainActivity

我有2个班,MainActivityasynch 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,但我不知道究竟是什么。
那么,假设我想在asynch-task完成后在我的MainActivity中显示Toast?

回答

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 
    } 
} 
+0

所以我正在为'interface'制作一个单独的类? – Bigflow 2013-05-06 14:42:12

+0

ofcourse。 AFAIK它的最佳途径 – 2013-05-06 14:43:34

+0

对于简单地显示一个“吐司”,只是通过“活动上下文”是最好和最简单的方法,恕我直言 – codeMagic 2013-05-06 14:47:33

0

如果您在MainActivity中没有调用某种方法,那么您不能在MainActivity的某个点开始行动。 AsyncTask的要点是允许您拨打Activity继续前进,而不是阻止UI。你可以做的是通过一个contextAsyncTask并显示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 contextToast