友链:汪菜菜

友链:隔壁老王

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);
    }
}

 

posted @   長安憶ღ  阅读(50)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示