Android Fragment无法使用onNewIntent()实现NFC扫描的替代方案咨询
解决方案
Fragment本身确实没有onNewIntent()系统回调,你可以通过以下方案实现基于Fragment生命周期独立管理NFC功能,无需把业务逻辑耦合到所属Activity中:
实现步骤
1. 定义NFC意图处理接口
在公共包中定义一个接口,用来统一接收NFC扫描事件:
public interface NfcIntentHandler { void handleNfcIntent(Intent intent); }
让你的两个负责不同NFC功能的Fragment都实现该接口,把你现在写在onNewIntent()中的业务逻辑全部移到接口实现的handleNfcIntent()方法中即可。
2. 所属Activity做轻量转发
仅需要在Activity的onNewIntent()回调中做意图转发,不需要写入任何NFC业务逻辑:
@Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); // 根据你使用的Fragment管理方式(普通FragmentManager/Navigation组件)调整获取当前前台Fragment的逻辑 Fragment currentForegroundFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (currentForegroundFragment instanceof NfcIntentHandler) { ((NfcIntentHandler) currentForegroundFragment).handleNfcIntent(intent); } }
3. 修复现有代码的已知问题
你当前的代码存在几处会导致功能异常的问题,需要同步调整:
onCreateView方法中你先inflate布局初始化了控件,最后又重新inflate了一次布局返回,导致之前初始化的控件全部失效,修改为返回已初始化的View即可:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_heart_beat, container, false); heartbearSearch = v.findViewById(R.id.heartBeat_Search); heartbearSuccess = v.findViewById(R.id.heartBeat_Success); heartbearSearch.setVisibility(View.VISIBLE); heartbearSuccess.setVisibility(View.GONE); // 不要重复inflate布局,直接返回已初始化的v return v; }
- 创建AlertDialog时不能使用ApplicationContext,必须传入Activity实例,否则会触发窗口类型报错:
AlertDialog alert = new AlertDialog.Builder(getActivity()).create();
- 安卓12及以上版本创建
PendingIntent必须明确指定可变性flag,PendingIntent.getActivity的最后一个参数需要修改为PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE,否则会直接崩溃。
方案优势
- 所有NFC业务逻辑完全内聚在对应Fragment中,不同Fragment可以独立实现不同的NFC处理逻辑,和Fragment生命周期完全绑定
- Activity仅做意图转发,不耦合任何NFC业务代码,后续新增NFC相关Fragment也不需要修改Activity逻辑
内容的提问来源于stack exchange,提问作者SLR
相关产品推荐
相关产品推荐

