我有个问题。我正在创建一个应用程序,您可以在其中购买可乐,芬达,水或其他任何东西。因此,当您选择要购买的商品时,可以按按钮结帐。然后出现一个弹出窗口(如图所示),在该窗口中,用户被迫将NFC标签保持在设备附近以完成订单。仅当您看到弹出窗口时,才应激活NFC检测器。因此,当您选择想要获得的东西时,请不要将标签意外地握在设备上,它会执行某些操作。

你们能帮我吗?非常感谢你!

java - 仅在代码的特定位置检测nfc-LMLPHP

package com.nfc.netvision;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.common.util.NumberUtils;
import com.google.firebase.auth.FirebaseAuth;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Locale;

import static android.widget.Toast.*;

public class OrderActivity extends AppCompatActivity implements OrderAdapter.TotalListener {

    private OrderAdapter adapter;
    private RecyclerView recyclerView;
    private ArrayList<ModelOrder> orderArrayList;
    private TextView textView_order_price, textView_order_count;
    private Dialog epicDialog;
    private Button btnCheckout, btnAbort;


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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order);

        recyclerView = findViewById(R.id.recyclerview_order_scroll);
        textView_order_price = findViewById(R.id.textView_order_price);
        textView_order_count = findViewById(R.id.textView_order_count);
        btnCheckout = (Button) findViewById(R.id.btnCheckout);


        orderArrayList = new ArrayList<>();
        orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
        orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
        orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
        orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        RecyclerView.LayoutManager recLiLayoutManager = layoutManager;

        recyclerView.setLayoutManager(recLiLayoutManager);

        adapter = new OrderAdapter(this, orderArrayList);

        recyclerView.setAdapter(adapter);

        epicDialog = new Dialog(this);

        btnCheckout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showWaitingPopUp();


            }
        });


    context = this;
        nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (nfcAdapter == null) {
            // Stop here, we definitely need NFC
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
        }
        readFromIntent(getIntent());

        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
        writeTagFilters = new IntentFilter[] { tagDetected };




    }

    // Read from NFC Tag
    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("NFC Content: " + text);
    }

    // Pop Up
    private void showWaitingPopUp() {
        if(adapter.getTotalPrice() != 0) {
        epicDialog.setContentView(R.layout.order_popup_waiting);
        epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        btnAbort = (Button) epicDialog.findViewById(R.id.btnAbort);
        // ONLY HERE NFC SHOULD BE CHECKING
        btnAbort.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set all orders count to 0
                for (ModelOrder modelOrder: orderArrayList) {
                    modelOrder.setCounter(0);
                }
                // Notify RecyclerView about the changes
                adapter.notifyDataSetChanged();
                NumberFormat n = NumberFormat.getCurrencyInstance(Locale.GERMANY);
                textView_order_price.setText( n.format(0));
                textView_order_count.setText(0 + "");

                epicDialog.dismiss();
            }
        });
        epicDialog.show();
        }
        else {
            Toast.makeText(this, "Keine Auswahl = Kein Essen", Toast.LENGTH_SHORT).show();
        }
    }

    @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 onTotalChanged(String result) {
        NumberFormat n = NumberFormat.getCurrencyInstance(Locale.GERMANY);
        textView_order_price.setText( n.format(Integer.parseInt(result)));
    }

    @Override
    public void onCountChanged(String result) {
        textView_order_count.setText(result);

    }

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

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


    private void WriteModeOn(){
        writeMode = true;
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, writeTagFilters, null);
    }

    private void WriteModeOff(){
        writeMode = false;
        nfcAdapter.disableForegroundDispatch(this);
    }
}

最佳答案

您可以执行与writeMode布尔标志相同的操作。

将另一个名为say nfcEnabled的布尔值作为OrderActivity类的成员,其默认值为false

在您的showWaitingPopUp()中,将该标志设置为true

如果onNewIntent标志不是nfcEnabled,则在true中跳过标签读取
例如
if (!nfcEnabled) return;

然后,当您成功地从标签中读取了正确的数据后,将nfcEnabled设置为false,如果已读取NDEF消息但其内容不正确,则可以将标记保留在true可以呈现出Tage。

08-17 04:04