何时可以在开始新活动时运行远程异步调用

时间:2015-03-09 20:49:55

标签: java android android-activity android-fragments android-asynctask

这是一种设计方法,因为我是Android新手 我有一个片段向用户显示一些数据 用户按下按钮然后我应该在另一个片段中显示项目列表。在向远程服务器发出请求之后,这个项目列表出现了 问题:拨打远程请求的电话的最佳位置在哪里?
在创建将显示的活动之前运行它,并以某种方式将它们传递给将显示它们的活动/片段,或者启动活动/片段并在onCreate上进行远程调用(当然是通过异步任务)?

2 个答案:

答案 0 :(得分:0)

这实际上取决于任务及其与其他组件的关系。这项任务是否与各自的脆弱/活动密切相关?然后,您可以启动组件,向用户显示进度,然后显示适当的结果。 它是否松散耦合,那么你可以实现一个发布/订阅消息,如机制,其中组件订阅任务,任务发布其结果,当它们准备好或订阅者甚至可以在必要时提取数据。

这取决于你和你想要完成的事情。

答案 1 :(得分:0)

如果我查看Fragment lifecycle,我相信在Fragment#onResume()方法中启动异步调用是个好主意。

异步通话所需的所有数据都可以通过Bundle

发送

示例:

MainActivity:

SearchResultFragment newFragment = new SearchResultFragment ();
Bundle args = new Bundle();
args.putInt("searchinput", input.getText()); // input from other fragment will be send to the MainActivity
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();

片段:

public void onResume(){
    super.onResume();
    ...
    Bundle b = getAttributes();
    String searchInput = b.getString("searchinput"); 
    asyncSearch(searchInput);
}

别忘了。每次片段从后栈返回布局时,都会调用onResume()方法。所以也许你应该使用一些布尔标志:

public void onResume(){
    super.onResume();
    ...
    if(startSearchTask){
        Bundle b = getAttributes();
        String searchInput = b.getString("searchinput"); 
        asyncSearch(searchInput); // sets startSearchTast -> FALSE
    }
}