Android 动态注册NFC

来源:互联网 发布:ubuntu 下载 编辑:程序博客网 时间:2024/06/03 03:44
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;
    }

本文固定链接:http://www.yemaoba.com/?post=31   
本文由ITcoder原创或编辑,互联分享,尊重版权,转载请以链接形式标明本文地址
0 0