Nfc扫描标签使Mainactivity重新启动

时间:2019-03-14 06:34:37

标签: android nfc scanning

我的android应用只有1个活动,即Mainactivity,并且有一个BottomNavigation菜单。完整的应用程序仅包含1个活动,然后在该单个活动中添加片段。

在我的NFC扫描片段中,我正在启动nfc适配器。以下是此NFC扫描片段的功能:-

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_complete_tour,container, false);

NfcAdapter mAdapter = NfcAdapter.getDefaultAdapter(mainActivity);

        mPendingIntent = PendingIntent.getActivity(
                getContext(),
                0,
                new Intent(getContext(), getContext().getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                0);

        mNdefPushMessage = new NdefMessage(new NdefRecord[]{newTextRecord(
                "Message from NFC Reader :-)", Locale.ENGLISH, true)});

return view;
}  

private NdefRecord newTextRecord(String text, Locale locale, boolean encodeInUtf8) {
    byte[] langBytes = locale.getLanguage().getBytes(Charset.forName("US-ASCII"));
    Charset utfEncoding = encodeInUtf8 ? Charset.forName("UTF-8") : Charset.forName("UTF-16");
    byte[] textBytes = text.getBytes(utfEncoding);
    int utfBit = encodeInUtf8 ? 0 : (1 << 7);
    char status = (char) (utfBit + langBytes.length);
    byte[] data = new byte[1 + langBytes.length + textBytes.length];
    data[0] = (byte) status;
    System.arraycopy(langBytes, 0, data, 1, langBytes.length);
    System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
    return new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT, new byte[0], data);
}

 @Override
public void onResume() {
    super.onResume();

        /* Nfc tour */
        if (mAdapter != null) {
            if (!mAdapter.isEnabled()) {
                showWirelessSettingsDialog();
            }
            mAdapter.enableForegroundDispatch(mainActivity, mPendingIntent, null, null);
            mAdapter.enableForegroundNdefPush(mainActivity, mNdefPushMessage);
        }

}

@Override
public void onPause() {
    super.onPause();
    if (mAdapter != null) {
        mAdapter.disableForegroundDispatch(mainActivity);
        mAdapter.disableForegroundNdefPush(mainActivity);
    }
}

0 个答案:

没有答案