从单独的asynctask调用片段方法

时间:2015-08-28 02:50:39

标签: android android-fragments android-asynctask

我有两个片段,Tab1和Tab2。 Tab1调用我的AsyncTask,在onPostExecute中,我试图让它调用Tab2 refreshData()方法。

我尝试查看Access fragment method from asynctask postexecute,但我无法弄清楚如何简单地将Tab2用作AsyncTask参数。

任何见解或者如果有更好的方法可以做到这一点将非常感激。

1 个答案:

答案 0 :(得分:0)

您应该使用onPostExecute AsyncTask方法向 Tab2 片段中的Receiver发送广播。

广播内容:(在您的AsyncTask中)

Intent intent = new Intent("someFilter");
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

您还可以使用putExtra()将原始类型和对象作为附加内容传递。

接收广播:(在您的Tab2片段中)

// declare the receiver as an atribute of your fragment
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        refreshData();
    }
};

// add this to onCreateView
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, new IntentFilter("someFilter"));

// add this to onDestroy
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);

在创建意图和注册接收器时,请注意您使用的IntentFilter。他们必须匹配否则不会发生任何事情。

总之,通过使用它,您不需要将片段作为参数传递给AsyncTask。

相关问题