简体   繁体   English

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

[英]replacement method for onNewIntent() in android fragment

I am developing a NFC app using Fragments.我正在使用 Fragments 开发 NFC 应用程序。 the fragment class will not let me use onNewIntent() for me to be able to make the app scan NFC tags.片段类不会让我使用 onNewIntent() 来让应用程序扫描 NFC 标签。 Is there a replacement function or work around to this issue.是否有替换功能或解决此问题。 below are the methods I am using in the Fragment class.下面是我在 Fragment 类中使用的方法。 I have two fragments which are responsible for different NFC functions.我有两个片段负责不同的 NFC 功能。 I need to be able to manage the NFC functionality using the fragment lifecycle individually rather than passing data to the fragment activity.我需要能够单独使用片段生命周期管理 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, container, 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(), 0, 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, toastMessage, duration).show();
        // NFC is not available for device
    } else if (!_nfcAdapter.isEnabled()) {
        CharSequence toastMessage = "Please Enable NFC!";
        Toast.makeText(context, toastMessage, duration).show();
        // NFC is available for device but not enabled
    } else {
        CharSequence toastMessage = "NFC enabled!";
        Toast.makeText(context, toastMessage, duration).show();
        // NFC is enabled
    }
}

Really NFC is an Activity scoped operation and really needs to be handled in your Activity.真正的 NFC 是一个活动范围的操作,确实需要在您的活动中处理。

Some parts like configuring can be done in Fragments but the actual interaction with the Tag data should be done in the Activity whether you are using the Manifest, ForegroundDispatch or enableReaderMode.有些部分如配置可以在 Fragments 中完成,但与 Tag 数据的实际交互应该在 Activity 中完成,无论您使用的是 Manifest、ForegroundDispatch 还是 enableReaderMode。

You need to turn your thinking on it's head to get what you want.你需要把你的想法转过来才能得到你想要的。

Have your NFC handling code in the Activity but make it conditional on what it does based on which fragment is active.将您的 NFC 处理代码放在 Activity 中,但根据哪个片段处于活动状态,使其以执行的操作为条件。

eg some pseudo code例如一些伪代码

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

There are various ways to doing this with the Fragment communicating to the activity that it it the "current" fragment when it is created and the Activity communicates back the processed data for the Fragment to use.有多种方法可以通过 Fragment 与 Activity 通信,在创建它时它是“当前” Fragment,并且 Activity 将处理后的数据通信回供 Fragment 使用。

Some option are interfaces for the Activity to Fragment communication.一些选项是 Activity 到 Fragment 通信的接口。

Or I think a better method is a shared view model as it is very easy for the Fragment to observe the shared view model to get notified when the Activity has finished processing the NFC data.或者我认为更好的方法是共享视图模型,因为 Fragment 很容易观察共享视图模型,以便在 Activity 完成处理 NFC 数据时得到通知。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM