从一个活动启动AsyncTask,在另一个活动中获得结果



我是Android编程的新手,我想创建一个中央数据库服务类,它将与外部数据库进行用户数据交换。为此,我创建了一个在成功登录后启动的服务。我创建了另一个类,它扩展AsyncTask来执行数据检索。现在,我希望将数据检索的方法存储在服务中。我将从不同的活动向服务发送意图,并且使用.setAction(),我将确定要调用哪个方法,或者要检索哪些数据。

我还创建了一个接口类来处理AsyncTask结果。现在,从这个问题来看,我认为有可能有多个监听器到同一个AsyncTask结果。但是现在这似乎是不可能实现的:我想在MainMenuActivity中检索AsyncTask结果,但是我不能在那里创建AsyncUserData的实例作为UserData类的委托。在下面的示例中,缺失的部分是UserData类要使用的AsyncUserData的有效实例。我怎么能做到呢?

示例如下:MainMenuActivity

public class MainMenuActivity extends ActionBarActivity implements AsyncUserData {
  TextView tvUsername;
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_menu);
    tvUsername =
      (TextView) findViewById(R.id.tvUsername);
    TelephonyManager tManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    String uid = tManager.getDeviceId();
    getDataFromUserSessionService(this, uid);
  }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main_menu, menu);
    return true;
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
      return true;
    }
    return super.onOptionsItemSelected(item);
  }
  @Override
  public void retrieveResult(String result) throws JSONException {
    JSONObject jsonObject = new JSONObject(result);
    String joName;
    joName = jsonObject.getJSONObject("name").toString();
    user.setName(joName);
    tvUsername.setText(joName);
  }
  public void getDataFromUserSessionService(Context context, String uid) {
    Intent intent = new Intent(context, UserSession.class);
    intent.setAction(UserSession.ACTION_FETCH_USER_DATA);
    intent.putExtra(UserSession.UID, uid);
    context.startService(intent);
  }

UserSession Service

public class UserSession extends IntentService {
  public static final String ACTION_FETCH_USER_DATA = "com.example.blahblah.services.action.read_user_data";
  @Override
  protected void onHandleIntent(Intent intent) {
    if (intent != null) {
      utils = new Utils(this);
      final String action = intent.getAction();
      uid = intent.getStringExtra(UID);
      if (ACTION_FETCH_USER_DATA.equals(action)) {
        handleUserDataFetch(uid);
      }
    }
  }
  private void handleUserDataFetch(String uid) {
    String[] parameters = new String[2];
    parameters[0] = uid;
    parameters[1] = Constants.USER_DATA_FETCH;
    UserData userData = new UserData(this);
    userData.execute(parameters);
  }

UserData AsyncTask类(Utils类只是有另一个post方法):

public class UserData extends AsyncTask < String, Void, String > {
  public AsyncUserData delegate = null;
  private Context myContext;
  public UserData(Context context) {
    myContext = context;
  }
  @Override
  protected String doInBackground(String...params) {
    String serverResponse = "";
    String uid = params[0];
    Utils utils = new Utils(myContext);
    String phpName = params[1];
    List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
    nameValuePairs.add(new BasicNameValuePair("uid", uid));
    try {
      serverResponse = utils.passDataToServer(phpName, nameValuePairs);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return serverResponse;
  }
  protected void onPostExecute(String result) {
    try {
      delegate.retrieveResult(result);
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }
};

AsyncUserData接口:

public interface AsyncUserData {
  void retrieveResult(String result) throws JSONException;
}

你可以使用Singleton来存储对activity的引用

    public class ServiceToActivity
    {
                public ActionBarActivity mainactivity = null;
                private static ServiceToActivity singleton = null;
                public Class<?> cl = null;
                private ServiceToActivity()
                {
                }
                public static ActionBarActivity getSingleton()
                {
                    if(singleton==null)
                           return null;
                    return singleton.mainactivity;
                }
               public static Class<?> getSingletonClass()
                {
                    if(singleton==null)
                           return null;
                    return singleton.cl;
                }
                public static void setSingleton(ActionBarActivity mainactivity, Class<?> cl)
                {
                      if(singleton==null)
                             singleton = new ServiceToActivity();
                      singleton.mainactivity = mainactivity;
                      singleton.cl = cl;
                }
    }

然后在服务启动前创建单例

  public void getDataFromUserSessionService(Context context, String uid) {
Intent intent = new Intent(context, UserSession.class);
intent.setAction(UserSession.ACTION_FETCH_USER_DATA);
intent.putExtra(UserSession.UID, uid);
ServiceToActivity.setSingleton(this,this.getClass());   //create Singleton to store a reference to the activity
context.startService(intent);
}

在UserData中检索数据到主活动:

 protected void onPostExecute(String result) {
try {
  Class<?> cl = ServiceToActivity.getSingletonClass();
  Method met = cl.getMethod("retrieveResult", String); //String because result is of type String: you can use result.getClass() instead
  met.invoke(cl.cast(ServiceToActivity.getSingleton()), result); // compare it to this ServiceToActivity.getSingleton().retrieveResult(result);
} catch (JSONException e) {
  e.printStackTrace();
}
}

听起来您可能想使用otto等事件总线

相关内容

  • 没有找到相关文章

最新更新