簡體   English   中英

onEvent()沒有被調用?

[英]onEvent() is not being called?

我將數據從AsyncTask傳遞到選項卡式活動的片段。 為什么沒有調用EventBus的onEvent()

BackgroundWorker.java doInBackground()由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() 我哪里錯了?

如果你在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", "");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM