How To Use Method Onnewintent(intent Intent) Inside A Fragment?
I'm trying to use NFC Hardware from my device. But, the problem is that when I register the Activity to receive the Intent: PendingIntent pendingIntent = PendingIntent.getActivity(
Solution 1:
onNewIntent
belongs to Activity so you cannot have it in your fragment. What you can do is pass the data to your fragment when it arrives in onNewIntent
provided you have the reference to the fragment.
Fragment fragment;
@OverrideprotectedvoidonNewIntent(Intent intent) {
super.onNewIntent(intent);
// Check if the fragment is an instance of the right fragmentif (fragment instanceof MyNFCFragment) {
MyNFCFragmentmy= (MyNFCFragment) fragment;
// Pass intent or its data to the fragment's method
my.processNFC(intent.getStringExtra());
}
}
Solution 2:
I fixed my issue the following way:
in MyActivity.java
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
in MyFragment.java
@OverridepublicvoidonStart() {
super.onStart();
if (getActivity() != null && getActivity().getIntent().hasExtra(...)) {
// do whatever needed
}
}
Solution 3:
Using LiveData
:
Repository:
classIntentRepo{
privateval _intent = MutableLiveData<Intent>()
valget: LiveData<Intent> = Transformations.map(_intent) { it!! }
funset(intent: Intent) { _intent.value = intent }
}
Activity ViewModel:
classMainViewModel(intentRepo: IntentRepo) : ViewModel() {
val intent = intentRepo
}
Activity
overridefunonNewIntent(intent: Intent?) {
super.onNewIntent(intent)
viewModel.intent.set(intent)
}
Fragment
viewModel.intent.get.observe(viewLifecycleOwner, {
// Your intent: $it
})
Solution 4:
We handled the call in a more dynamic way to support any fragment, by having in the Activity
something like:
// ...publicclassActivityMainextendsAppCompatActivity {
// ...@OverrideprotectedvoidonNewIntent(Intent intent) {
super.onNewIntent(intent);
Fragmentfragment= getFragment();
if (fragment != null) {
try {
Methodmethod= 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() {
// For NAVIGATION-DRAWER only// (replace below logic, if you use View-Pager).FragmentManagermanager=this.getSupportFragmentManager();
manager.executePendingTransactions();
return manager.findFragmentById(R.id.my_main_content);
}
}
Then in each root Fragment
simply listen:
@SuppressWarnings("unused")publicvoidonNewIntent(Intent intent) {
Log.i("MyTag", "onNewIntent: " + intent);
}
Post a Comment for "How To Use Method Onnewintent(intent Intent) Inside A Fragment?"