package com.dayu.recharge.tools;
|
|
import android.app.Activity;
|
import android.content.Context;
|
import android.nfc.NfcAdapter;
|
import android.nfc.Tag;
|
import android.util.Log;
|
import android.widget.Toast;
|
|
/**
|
* Created by Android Studio.
|
* author: zuo
|
* Date: 2023-11-30
|
* Time: 10:27
|
* 备注:
|
*/
|
public class NFCUtil {
|
static String TAG = "NFCUtil";
|
static NFCUtil nfcUtil;
|
static NfcAdapter mNfcAdapter;
|
public static int READER_FLAGS =
|
NfcAdapter.FLAG_READER_NFC_A | NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK;
|
private static boolean isOpen = false;
|
|
LoyaltyCardReader.AccountCallback accountCallback;
|
|
public void setAccountCallback(LoyaltyCardReader.AccountCallback accountCallback) {
|
this.accountCallback = accountCallback;
|
}
|
|
/**
|
* 获取NFC的单例
|
*
|
* @return NfcUtils
|
*/
|
public static NFCUtil getInstance() {
|
if (nfcUtil == null) {
|
synchronized (NFCUtil.class) {
|
if (nfcUtil == null) {
|
nfcUtil = new NFCUtil();
|
}
|
}
|
}
|
return nfcUtil;
|
}
|
|
/**
|
* 在onStart中检测是否支持nfc功能
|
*
|
* @param context 当前页面上下文
|
*/
|
public void onStartNfcAdapter(Activity context) {
|
mNfcAdapter = NfcAdapter.getDefaultAdapter(context);//设备的NfcAdapter对象
|
if (mNfcAdapter == null) {//判断设备是否支持NFC功能
|
Toast.makeText(context, "设备不支持NFC功能!", Toast.LENGTH_SHORT).show();
|
context.finish();
|
return;
|
}
|
if (!mNfcAdapter.isEnabled()) {//判断设备NFC功能是否打开
|
Toast.makeText(context, "请到系统设置中打开NFC功能!", Toast.LENGTH_SHORT).show();
|
return;
|
}
|
Log.d(TAG, "NFC is start");
|
}
|
|
/**
|
* 在onResume中开启nfc功能
|
*
|
* @param activity
|
*/
|
public void onResumeNfcAdapter(Activity activity) {
|
if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
|
// mNfcAdapter.enableForegroundDispatch(this,mPendingIntent,null,null);//打开前台发布系统,使页面优于其它nfc处理.当检测到一个Tag标签就会执行mPendingItent
|
if (!isOpen)
|
mNfcAdapter.enableReaderMode(activity, new LoyaltyCardReader(activity, accountCallback),
|
READER_FLAGS,
|
null);
|
isOpen = true;
|
Log.d(TAG, "Resume");
|
}
|
}
|
|
/**
|
* 在onPause中关闭nfc功能
|
*
|
* @param activity
|
*/
|
public void onPauseNfcAdapter(Activity activity) {
|
if (mNfcAdapter != null && mNfcAdapter.isEnabled()) {
|
if (isOpen)
|
mNfcAdapter.disableReaderMode(activity);
|
isOpen = false;
|
}
|
Log.d("myNFC", "onPause");
|
}
|
|
|
|
|
}
|