Android 动态注册NFC

1、不能用用广播的形式去注册NFC的action

    实现代码
    
  private NfcAdapter mAdapter;
   
    private String[][] techList;
   
    private IntentFilter[] intentFilters;
   
    private PendingIntent pendingIntent;

    @Override
    protected void onResume()
    {
        super.onResume();
        // 使用前台发布系统
        mAdapter.enableForegroundDispatch(this, pendingIntent, intentFilters, techList);
    }
    
 public void onNewIntent(Intent intent)
    {
        if (!initNFC)
        {
            Toast.makeText(this, "NFC功能初始化失败!", Toast.LENGTH_SHORT).show();
            return;
        }
        pre = new ProgersssDialog(this);
        pre.setOnKeyListener(this);
        this.intent = intent;
        mHandler.postDelayed(mUpdateResults, 100);
        return;
    }


    //初始化NFC
    private boolean initNFC()
    {
        // 获取nfc适配器
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mAdapter == null)
        {
            Toast.makeText(this, "设备不支持NFC功能!", Toast.LENGTH_SHORT).show();
            return false;
        }
        if (mAdapter != null && !mAdapter.isEnabled())
        {
            Toast.makeText(this, "请在系统设置中先启用NFC功能!", Toast.LENGTH_SHORT).show();
            return false;
        }
        // 定义程序可以兼容的nfc协议,例子为nfca和nfcv
        // 在Intent filters里声明你想要处理的Intent,一个tag被检测到时先检查前台发布系统,
        // 如果前台Activity符合Intent filter的要求,那么前台的Activity的将处理此Intent。
        // 如果不符合,前台发布系统将Intent转到Intent发布系统。如果指定了null的Intent filters,
        // 当任意tag被检测到时,你将收到TAG_DISCOVERED intent。因此请注意你应该只处理你想要的Intent。
        techList = new String[][] {new String[] {android.nfc.tech.NfcV.class.getName()}, new String[] {android.nfc.tech.NfcA.class.getName()}};
        intentFilters = new IntentFilter[] {new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED),};
        // 创建一个 PendingIntent 对象, 这样Android系统就能在一个tag被检测到时定位到这个对象
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        return true;
    }

本文由 ITcoder原创或编辑,互联分享,尊重版权,转载请以链接形式标明本文地址
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值