android片段中onNewIntent()的替换方法

如何解决android片段中onNewIntent()的替换方法

我正在使用 Fragments 开发 NFC 应用。片段类不会让我使用 onNewIntent() 来让应用程序扫描 NFC 标签。是否有替换功能解决此问题。下面是我在 Fragment 类中使用的方法我有两个片段负责不同的 NFC 功能。我需要能够单独使用片段生命周期来管理 NFC 功能,而不是将数据传递给片段活动。

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_ParaM1);
        mParam2 = getArguments().getString(ARG_ParaM2);
    }
    _nfcAdapter = NfcAdapter.getDefaultAdapter(getActivity().getApplicationContext());
    CheckNfcStatus();

    NfcManager manager = (NfcManager) getActivity().getApplicationContext().getSystemService(Context.NFC_SERVICE);
    NfcAdapter adapter = manager.getDefaultAdapter();
}

@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    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);
    
    return inflater.inflate(R.layout.fragment_heart_beat,false);
}


protected String TagUid;

@Override
public void onResume() {
    //CheckNfcStatus();
    AlertDialog alert = new AlertDialog.Builder(getActivity().getApplicationContext()).create();
    super.onResume();
    if (_nfcAdapter == null) {                           // checks if NFC is available on the device
        alert.setMessage("NFC is not supported on this device.");
        alert.setTitle("NFC Unavailable");
        alert.show();
    }
    else {
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_disCOVERED);

        Intent intent = new Intent(getActivity().getApplicationContext(),getClass());
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

        final PendingIntent pendingIntent = PendingIntent.getActivity(getActivity().getApplicationContext(),intent,0);

        IntentFilter[] filters = new IntentFilter[]{
                new IntentFilter(NfcAdapter.ACTION_TECH_disCOVERED),};
        String[][] techList = new String[][]{
                new String[]{NfcA.class.getName()},new String[]{NfcB.class.getName()},new String[]{NfcF.class.getName()},new String[]{NfcV.class.getName()},new String[]{NfcBarcode.class.getName()
                },// Filter for nfc tag discovery
        };
        _nfcAdapter.enableForegrounddispatch(getActivity(),pendingIntent,filters,techList);
    }
}

@Override
public void onPause() {
    super.onPause();
    _nfcAdapter.disableForegrounddispatch(getActivity());
}

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    HBClass hb = new HBClass();

    if (intent.getAction() == NfcAdapter.ACTION_TECH_disCOVERED) {
        Boolean res = true;

        if (res) {
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            if (tag != null) {
                if (hb.ReadTagSync(tag)) {
                    Context context = getContext();
                    mheartimage.startAnimation(mHeartAnimation);

                    CharSequence toastMessage = "Transmission successful";
                    int duration = Toast.LENGTH_SHORT;
                    Toast.makeText(context,toastMessage,duration).show();

                    textView.setText("Scan a new Tag");
                }
            }
        }
    }
}


public void SendRWBool(boolean someval) {

    writeFlag = true;
    //WriteNFC(tg);
}

private void CheckNfcStatus() {
    Context context = getActivity().getApplicationContext();
    int duration = Toast.LENGTH_LONG;
    if (_nfcAdapter == null) {
        CharSequence toastMessage = "No NFC available for the device!";
        Toast.makeText(context,duration).show();
        // NFC is not available for device
    } else if (!_nfcAdapter.isEnabled()) {
        CharSequence toastMessage = "Please Enable NFC!";
        Toast.makeText(context,duration).show();
        // NFC is available for device but not enabled
    } else {
        CharSequence toastMessage = "NFC enabled!";
        Toast.makeText(context,duration).show();
        // NFC is enabled
    }
}

解决方法

真正的 NFC 是一个 Activity 范围的操作,确实需要在您的 Activity 中处理。

有些部分如配置可以在 Fragments 中完成,但与 Tag 数据的实际交互应该在 Activity 中完成,无论您使用的是 Manifest、ForegroundDispatch 还是 enableReaderMode。

为了得到你想要的东西,你需要把你的想法转过来。

在 Activity 中包含您的 NFC 处理代码,但根据哪个片段处于活动状态,使其以执行的操作为条件。

例如一些伪代码

handleNfc() {
  if current fragment equal Fragment 1 {
    // Process NFC the Fragment 1 way
  } else {
    // Process NFC the Fragment 2 way
  }
}

有多种方法可以做到这一点,其中 Fragment 在创建时向 Activity 传达它是“当前”的 Fragment,而 Activity 将处理后的数据传达回供 Fragment 使用。

某些选项是 Activity 到 Fragment 通信的接口。

或者我认为更好的方法是共享视图模型,因为 Fragment 很容易观察共享视图模型,以便在 Activity 完成处理 NFC 数据时得到通知。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?