如何在一个活动中开始处理异步任务,并在OnBackground上完成工作时通知另一个活动

时间:2012-12-05 08:02:13

标签: android android-asynctask

我想实现以下行为,但我不确定如何:

   1. User start an activity
   2. Activity starts an AsyncTask
   3. After initiating the AsyncTask,the control is transferred to another activity.
   4. Now,when the AsynTask finishes its work,the 2nd activity should get to know that        AsyncTask has completed its working in the previous activity.

我不知道如何实现这一功能。I know how to use AsyncTask但我不知道如何通知除其父活动之外的任何活动有关其工作的完成情况。请帮助我。谢谢。

我想这样做是因为在第一个活动中我想开始在AsyncTask中工作,然后控件转移到第二个活动但AsyncTask仍在运行。当AsyncTask完成其功能时,我想通知第二个关于它的活动,然后想在第二个活动中执行一些功能。

2 个答案:

答案 0 :(得分:2)

您可以创建interface,将其传递给AsyncTask(在构造函数中),然后在onPostExecute中调用接口方法..并使您的第二个活动实现此接口.. < / p>

例如:

您的界面:

public interface OnTaskCompleted {
    void onTaskCompleted();
}

你的第二个活动:

public MyActivity implements OnTaskCompleted {
    //your Activity
}

你的AsyncTask:

public YourTask extends AsyncTask<Object,Object,Object> { //change Object to required type
    private OnTaskCompleted listener;

    public YourTask(OnTaskCompleted listener) {
        this.listener=listener;
    }

    //required methods

    protected void onPostExecute(Object o) {
        //your stuff
        listener.onTaskCompleted();
    }
}

答案 1 :(得分:1)

  • 在第二个活动中创建BroadcastReceiver并使用注册它 registerReceiver()方法。
  • sendBroadcast()在AsyncTask onPostExecute()方法中的第一个 活性。

    public class SecondActivity extends Activity {
        private BroadcastReceiver myBroadcastReceiver =
            new BroadcastReceiver() {
                @Override
                public void onReceive(...) {
                    ...
                }
           });
    
        ...
    
        public void onResume() {
            super.onResume();
            IntentFilter filter = new IntentFilter();  
                        filter.addAction("com.example.asynctaskcompleted");  
                        filter.addCategory("android.intent.category.DEFAULT");
            registerReceiver(myBroadcastReceiver, filter);
        }
    
        public void onPause() {
            super.onPause();
            ...
            unregisterReceiver(myBroadcastReceiver);
        }
        ...
    }
    
    
    public class FirstActivity extends Activity {
        private class MyTask extends AsyncTask<Void, Void, Void> {
            protected Void doInBackground(Void... args) {
            ...
        }    
    
        protected void onPostExecute(Void result) {
            Intent intent = new Intent ("com.example.asynctaskcompleted");            
    
            FirstActivity.this.sendBroadcast(intent);
     }
    

    }