package com.example.wms;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.widget.Toast;
import androidx.fragment.app.FragmentActivity;
public class BaseNfcActivity extends FragmentActivity {
protected NfcAdapter mNfcAdapter;
private PendingIntent mPendingIntent;
@Override
protected void onStart() {
super.onStart();
//此处adapter需要重新获取,否则无法获取message
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
//一旦截获NFC消息,就会通过PendingIntent调用窗口
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);
if (!ifNFCUse()) {
Toast.makeText(this, "请在系统中打开nfc功能!",Toast.LENGTH_LONG).show();
}
}
//检测工作,判断设备的NFC支持情况
protected boolean ifNFCUse() {
if (mNfcAdapter == null) {
Toast.makeText(this, "设备不支持NFC!",Toast.LENGTH_LONG).show();
return false;
}
if (!mNfcAdapter.isEnabled()) {
Toast.makeText(this, "请在系统设置中先启用NFC功能!",Toast.LENGTH_LONG).show();
return false;
}
return true;
}
//获得焦点,按钮可以点击
@Override
public void onResume() {
super.onResume();
//设置处理优于所有其他NFC的处理
if (mNfcAdapter != null)
mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);
}
//暂停Activity,界面获取焦点,按钮可以点击
@Override
public void onPause() {
super.onPause();
//恢复默认状态
if (mNfcAdapter != null)
mNfcAdapter.disableForegroundDispatch(this);
}
}
原创文章,作者:kepupublish,如若转载,请注明出处:https://blog.ytso.com/272964.html