onEvent()没有被调用?

时间:2017-01-16 10:10:16

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

我将数据从AsyncTask传递到标签式活动的片段。为什么没有调用EventBus的onEvent()

BackgroundWorker.java doABackground()由MainActivity

调用
public class BackgroundWorker extends AsyncTask<String,Void,String> {

   @Override
   protected void onPostExecute(String line) {
     userResult =  line.split(" ");
     String result = userResult[0];

     if(result.equals("Success")){
       CustomMessageEvent event = new CustomMessageEvent();
       event.setCustomMessage(line);
       Intent intent = new Intent(context,TabActivity.class);
       intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       context.startActivity(intent);
       EventBus.getDefault().post(event);
     }
   }
}

ProfileTab.java此文件是选项卡式活动的片段。是否应该在选项卡式活动中完成任何操作,或者是否必须再次调用doInBackground。

public class ProfileTab extends Fragment {

  public TextView t1;
  private View rootView;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.profile, container, false);

    t1 = (TextView) rootView.findViewById(R.id.textView4);

    EventBus.getDefault().register(this);
    Log.d(TAG, "onCreateView: ");

    return rootView;
  }

  @Subscribe(threadMode = ThreadMode.ASYNC)
  public void onEventAsync(CustomMessageEvent event) {
    Log.d(TAG, "onEvent: ");
    t1.setText(event.getCustomMessage());
  }

}

尝试了LocalBroadcastManager并且结果相同,未调用onReceive()。我哪里错了?

1 个答案:

答案 0 :(得分:0)

如果你在onPostExecute中启动Activity,我建议按意图而不是事件传递数据 - 这更简单。 您的订阅方法未被调用,因为事件是在您注册之前发布的 - 使用postSticky代替post,您将获得一个事件。

我假设您要传递lineString)。所以构建意图:

Intent intent = new Intent(context,TabActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("LINE", line);
context.startActivity(intent);

在你的TabActivity onCreate中读取传递的值:

String line = getIntent().getStringExtra("LINE", "");