1

我正在将数据传递AsyncTask给选项卡式活动的片段。为什么onEvent()没有调用 EventBus?

BackgroundWorker.javadoInBackground() 由 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()没有被调用。我哪里错了?

4

1 回答 1

0

如果您在 Activity 中启动 Activity onPostExecute,我建议按意图传递数据,而不是事件 - 它更简单。您订阅的方法不会被调用,因为事件是在您注册之前发布的 - 使用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", "");
于 2017-01-16T10:12:18.437 回答