gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:46:07 25 4
gpt4 key购买 nike

我有一个问题。我正在创建一个应用程序,你可以在其中购买可乐、芬达、水或其他东西。因此,当您选择要购买的商品后,您可以按下结账按钮。然后会出现一个弹出窗口(如图所示),用户被迫将 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);
}
}

最佳答案

您可以执行类似于使用 writeMode boolean 标志执行的操作。

让另一个名为 nfcEnabled 的 boolean 值作为 OrderActivity 类的成员,默认值为 false

在您的 showWaitingPopUp() 中将该 Flag 设置为 true

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

然后,当您成功从标签读取正确的数据时,将 nfcEnabled 设置为 false,这样您就可以将标志保留为 true 如果读取了 NDEF 消息但内容不正确,则可以呈现另一个 Tage。

关于java - 仅在代码的特定位置检测nfc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61775362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com