1

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

   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 完成其功能时,我想通知第二个活动它然后想在第二个活动中执行一些功能。

4

2 回答 2

2

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

例如:

你的界面:

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();
    }
}
于 2012-12-05T08:05:04.260 回答
1
  • 在第二个活动中创建 BroadcastReceiver 并使用 registerReceiver() 方法注册它。
  • 第一个 Activity 的 AsyncTask onPostExecute() 方法中的 sendBroadcast()。

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

    }

于 2012-12-05T08:12:58.713 回答