我想要使用设备上的 NFC 硬件。但是,问题在于当我注册活动以接收 Intent 时:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
我收到了一个Activity返回的结果,而不是Fragment。有没有办法在Fragment中处理这个结果呢?
提前感谢!
我想要使用设备上的 NFC 硬件。但是,问题在于当我注册活动以接收 Intent 时:
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
我收到了一个Activity返回的结果,而不是Fragment。有没有办法在Fragment中处理这个结果呢?
提前感谢!
onNewIntent
属于 Activity,所以你无法在片段中使用它。你可以在 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());
}
}
以下是我解决问题的方法:
在MyActivity.java中:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
在MyFragment.java中
@Override
public void onStart() {
super.onStart();
if (getActivity() != null && getActivity().getIntent().hasExtra(...)) {
// do whatever needed
}
}
class IntentRepo {
private val _intent = MutableLiveData<Intent>()
val get: LiveData<Intent> = Transformations.map(_intent) { it!! }
fun set(intent: Intent) { _intent.value = intent }
}
活动 ViewModel:
class MainViewModel(intentRepo: IntentRepo) : ViewModel() {
val intent = intentRepo
}
活动
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
viewModel.intent.set(intent)
}
片段
viewModel.intent.get.observe(viewLifecycleOwner, {
// Your intent: $it
})
我们以更加动态的方式处理调用,以支持任何片段,在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() {
// For NAVIGATION-DRAWER only
// (replace below logic, if you use View-Pager).
FragmentManager manager = this.getSupportFragmentManager();
manager.executePendingTransactions();
return manager.findFragmentById(R.id.my_main_content);
}
}
然后在每个根Fragment
中简单地监听:
@SuppressWarnings("unused")
public void onNewIntent(Intent intent) {
Log.i("MyTag", "onNewIntent: " + intent);
}
onNewIntent
的生命周期等效方法是什么? - IgorGanapolsky