简体   繁体   English

如何将数据从一个活动传递到当前可见/活动活动? 这是一个好的共同点吗?

[英]How can I pass data from one Activity to the current visible/active Activity? Is it a good pattern in common?

I want to implement generic AsyncTasks factory in order not to write a lot of repeating code every time I want to run asynchronous operation.But I have a problem. 我想实现通用的AsyncTasks工厂,以免每次我想运行异步操作时都写很多重复的代码,但是我有一个问题。

So I want to define this factory class in GlobalActivity which every Activity which wants to use that AsyncTasks factory should subclass, but i need to use result of doInBackground method in every active Activity which is inherited from the GlobalActivity. 因此,我想在GlobalActivity中定义该工厂类,每个要使用该AsyncTasks工厂的Activity都应该为其子类,但是我需要在从GlobalActivity继承的每个活动Activity中使用doInBackground方法的结果。 My idea is to define in that class some method updateCurrentActivity() which every subclass must override and do some manipulations with that doInBackground result (displaying it eg). 我的想法是在该类中定义一些方法updateCurrentActivity(),每个子类都必须重写该方法,并对该doInBackground结果进行一些操作(例如显示)。 But how to handle this result I don't know. 但是我不知道如何处理这个结果。 Eg here is that factory onPostExecute definition: 例如,这是工厂的onPostExecute定义:

protected void onPostExecute(HashMap<String, Object> result)
    {  
        currentActivityData = result;
                   //How to pass that result to the current Active
                   //activity which is overriding this method?
        updateCurrentActivity();
    }

Is it a good idea in common to create such factory. 创建这样的工厂是否是一个共同的好主意。 Or best practice is to write new AsyncTask... every time I want to use AsyncTask? 还是最佳实践是每次我想使用AsyncTask时都编写new AsyncTask... AsyncTask?

You could create your MyTask class extending AsyncTask and pass a handler in constructor from the activity you want to do the task like 您可以创建扩展AsyncTask的MyTask类,并从要执行任务的活动中向构造函数传递处理程序

final Handler mHandler = new Handler() { 

  public void handleMessage(Message msg) 
  { 
       //get your data here
       int something = msg.arg1; 
  } 
}; 

public void myMethodInsideActivity{
    new MyTask(this, mHandler).execute();
}

and call this from your pre, progressUpdate or post of your task like this 然后从您的任务的pre,progressUpdate或发布中调用此命令

Message msg = new Message();
msg.arg1 = 1;
actHandler.sendMessage(msg);

This way you only have one task class and multiple instances, each one connected with it's activity via the handler 这样,您只有一个任务类和多个实例,每个实例都通过处理程序与其活动相关联

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM