Pass intent to my fragment

2019-02-19 23:42发布

问题:

I have implemented the NFC foreground dispatch in my Activity. The code works fine, when the NFC tag get close to my phone, the onNewIntent(Intent intent) is called.

Now, I would like to show an Fragment(MyFragment.java) when the onNewIntent(Intent intent) is invoked. There is resolveIntent(Intent intent) method defined in the Fragment class.

Here is some code of my Activity:

public class MainActivity extends Activity{
   …
   @Override
   public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

      FragmentManager fragmentManager = activity.getFragmentManager();
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

      //How to pass the 'intent' to MyFragment?
      MyFragment fragment = new MyFragment();

    fragmentTransaction.replace(R.id.placeholder, fragment, fragmentName);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
   }        
}

Code of MyFragment.java

public class MyFragment extends Fragment{
    …
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
       ...
    }
    @Override
    public void onResume(){
      super.onResume();

       //How to get 'intent' here 
       resolveIntent(intent);
    }

    private void resolveIntent(Intent intent){
       ...
    }
}

My question is how could I pass the intent from onNewIntent(Intent intent) to MyFragment so that I can handle the intent in MyFragment in onResume()?

回答1:

I figured out that Intent is an parcelable object, I can use bundle.putParcelable() method to pass the intent instance to the next fragment.



回答2:

You could store the intent in a field in your activity. Add a method like getLastIntent() and the call it in your fragment with getActivity().getLastIntent().

Or Extrat info from the intent and create a Bundle that you will use with fragment.setArguments() and in the onStart() method of your fragment use getArguments()