BaseNfcActivity
作者:互联网
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);
}
}
标签:Toast,NFC,mNfcAdapter,import,BaseNfcActivity,null,android 来源: https://www.cnblogs.com/changanyi/p/16354667.html