简体   繁体   English

如何在 Fragment 中使用方法 onNewIntent(Intent intent)?

[英]How to use method onNewIntent(Intent intent) inside a Fragment?

I'm trying to use NFC Hardware from my device.我正在尝试从我的设备使用 NFC 硬件。 But, the problem is that when I register the Activity to receive the Intent:但是,问题是当我注册 Activity 以接收 Intent 时:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

I receive the result in an Activity instead of a Fragment.我在活动而不是片段中收到结果。 Is there a way to handle this result inside a Fragment?有没有办法在 Fragment 中处理这个结果?

Thanks in advance!提前致谢!

onNewIntent belongs to Activity so you cannot have it in your fragment. onNewIntent属于 Activity,因此您不能在片段中使用它。 What you can do is pass the data to your fragment when it arrives in onNewIntent provided you have the reference to the fragment.您可以做的是在数据到达onNewIntent时将数据传递给您的片段,前提是您拥有对该片段的引用。

Fragment fragment;  
@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    // Check if the fragment is an instance of the right fragment
    if (fragment instanceof MyNFCFragment) {
        MyNFCFragment my = (MyNFCFragment) fragment;
        // Pass intent or its data to the fragment's method
        my.processNFC(intent.getStringExtra());
    }

}

I fixed my issue the following way:我通过以下方式解决了我的问题:

in MyActivity.java在 MyActivity.java 中

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

in MyFragment.java在 MyFragment.java 中

@Override
public void onStart() {
    super.onStart();
    if (getActivity() != null && getActivity().getIntent().hasExtra(...)) {
        // do whatever needed
    }
}

Using LiveData :使用LiveData

Repository:存储库:

class IntentRepo  {
    private val _intent = MutableLiveData<Intent>()

    val get: LiveData<Intent> = Transformations.map(_intent) { it!! }

    fun set(intent: Intent) { _intent.value = intent }
}

Activity ViewModel:活动视图模型:

class MainViewModel(intentRepo: IntentRepo) : ViewModel() {
    val intent = intentRepo
}

Activity活动

override fun onNewIntent(intent: Intent?) {
    super.onNewIntent(intent)
    viewModel.intent.set(intent)
}

Fragment分段

viewModel.intent.get.observe(viewLifecycleOwner, {
    // Your intent: $it
})

We handled the call in a more dynamic way to support any fragment, by having in the Activity something like:我们以更动态的方式处理调用以支持任何片段,通过在Activity包含以下内容:

// ...

public class ActivityMain extends AppCompatActivity {

    // ...

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Fragment fragment = getFragment();
        if (fragment != null) {
            try {
                Method method = fragment.getClass().getMethod("onNewIntent", Intent.class);
                method.invoke(fragment, intent);
            } catch (NoSuchMethodException ignored) {
            } catch (IllegalAccessException | InvocationTargetException e) {
                Log.e(TAG, "Failed to call onNewIntent method for class: " + fragment.getClass().getSimpleName());
            }
        }
    }

    public Fragment getFragment() {
        //if (BuildConfig.UI_NAVIGATION_DRAWER) {
            FragmentManager manager = this.getSupportFragmentManager();
            manager.executePendingTransactions();
            return manager.findFragmentById(R.id.my_main_content);
        //} else {
            // TODO: Handle view pager.
        //}
    }
}

And later in any Fragment implementation required:稍后在所需的任何Fragment实现中:

  @SuppressWarnings("unused")
  public void onNewIntent(Intent intent) {
    Log.i(TAG, "onNewIntent: " + intent);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM