在片段中使用onNewIntent(…)

问题描述 投票:0回答:2

我有问题。我想使用方法onNewIntent(...)getIntent(...)。不幸的是,片段不知道这个意图。如何在片段中使用此方法?这个片段应该能够读取NFC标签,所以我需要这个意图。我很高兴收到答复。我提前谢谢你。您可以在下面看到我的代码。

public class UserFragmentGeldaufladen extends Fragment {

    private Dialog epicDialog;

    private NfcAdapter nfcAdapter;
    private PendingIntent pendingIntent;
    private boolean writeMode;
    private IntentFilter writeTagFilters[];
    private Context context;
    private Tag myTag;

    private interface RetrievalEventListener<T> {
        abstract void onDataRetrieved(T t);
    }

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


        context = view.getContext();
        epicDialog = new Dialog(view.getContext());



        nfcAdapter = NfcAdapter.getDefaultAdapter(view.getContext());
        if (nfcAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(view.getContext(), "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
        }
        // Error
        readFromIntent(getIntent());
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(context, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);



        return view;

    }


    private void readFromIntent(Intent intent) {
        String action = intent.getAction();
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
                || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
            Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
            NdefMessage[] msgs = null;
            if (rawMsgs != null) {
                msgs = new NdefMessage[rawMsgs.length];
                for (int i = 0; i < rawMsgs.length; i++) {
                    msgs[i] = (NdefMessage) rawMsgs[i];
                }
            }
            buildTagViews(msgs);
        }
    }
    private void buildTagViews(NdefMessage[] msgs) {
        if (msgs == null || msgs.length == 0) return;

        String text = "";
//        String tagId = new String(msgs[0].getRecords()[0].getType());
        byte[] payload = msgs[0].getRecords()[0].getPayload();
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16"; // Get the Text Encoding
        int languageCodeLength = payload[0] & 0063; // Get the Language Code, e.g. "en"
        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");

        try {
            // Get the Text
            text = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
        } catch (UnsupportedEncodingException e) {
            Log.e("UnsupportedEncoding", e.toString());
        }

        System.out.println(text);
    }






    // Error
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        readFromIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            myTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        }
    }

    @Override
    public void onPause(){
        super.onPause();
        WriteModeOff();
    }

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


    private void WriteModeOn(){
        writeMode = true;
        nfcAdapter.enableForegroundDispatch((Activity) context, pendingIntent, writeTagFilters, null);
    }
    /******************************************************************************
     **********************************Disable Write*******************************
     ******************************************************************************/
    private void WriteModeOff(){
        writeMode = false;
        nfcAdapter.disableForegroundDispatch((Activity) context);
    }


}
java android android-studio android-intent nfc
2个回答
1
投票

您可以将getIntent()与片段一起使用,但需要先调用getActivity()。像getActivity().getIntent()...这样的东西可能起作用。


0
投票

我编写了一个示例代码来使onNewIntent方法起作用。添加接口类以与UserFragmentGeldaufladen片段通信您的片段活动

public interface OnNewIntentListener {
    void newIntent(Intent intent);
}

并且在片段活动中,添加接口变量和两个方法

private OnNewIntentListener mOnNewIntentListener;

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    if (mOnNewIntentListener != null) {
        mOnNewIntentListener.newIntent(intent);
    }
}

public void setOnNewIntentListener(OnNewIntentListener onNewIntentListener) {
    this.mOnNewIntentListener = onNewIntentListener;
}

现在,在UserFragmentGeldaufladen片段中,添加onCreate方法。首次开始活动时,您必须从活动中获取意图,例如@ Dante

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

    //get first time intent
    Intent intent = getActivity().getIntent();

    ((YourActivity)getActivity()).setOnNewIntentListener(new OnNewIntentListener() {
        @Override
        public void newIntent(Intent intent) {
            //handle your code here for each new intent
        }
    });
}

要在onNewIntent方法中接收意图,请更新您的活动调用

Intent i = new Intent(context, YourActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // -> this will be require, if you will be update your fragment from BroadcastReceiver or Service
startActivity(i);

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.