只在代码的某一位置检测nfc

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

我有一个问题。我正在创建一个应用程序,在那里你可以买东西,如可乐,芬达,水或任何东西。所以,当你选择了你要买的东西,你可以按按钮结账,然后出现一个弹出窗口(如图所示),用户被迫持有NFC标签。然后出现一个弹出窗口(如图所示),用户被迫拿着NFC标签靠近设备来完成订单。NFC检测器只有在你看到弹出窗口时才会被激活。所以,当你选择你想得到的东西时,你不会不小心拿着标签在设备上,它会做一些事情。

你们能帮我解决这个问题吗?非常感谢您!我有一个问题。

enter image description here

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);
    }
}
java android android-studio nfc
1个回答
0
投票

你可以做一些类似的事情,你已经做了什么与 writeMode 布尔运算标志。

有另一个布尔值叫做说 nfcEnabled 担任 OrderActivity 类,默认值为 false

在你的 showWaitingPopUp() 将该旗帜设置为 true

然后在 onNewIntent 如果标志 nfcEnabled 不是 true例如 if (!nfcEnabled) return;

然后,当你成功地从Tag中读取了正确的数据后,设置了 nfcEnabledfalse旗,这就允许你把旗帜留在 true 如果NDEF消息被读取,但它没有正确的内容,所以可以提出另一个Tage。

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