NFC 前台分发机制

来源:互联网 发布:手机安装ubuntu系统 编辑:程序博客网 时间:2024/05/16 18:03

NFC两种注册方式: manifest.xml 中注册,在系统发出广播时,所有在manifest.xml中注册的activity都会收到该广播,如果有多个,会提供给用户一个选择界面..........

使用前台分发机制,优先级高于manifest.xml注册方式.

nfc标签前台分发系统

什么叫nfc的前台发布系统?就是说当我们已经打开我们的应用的时候,那么通过这个前台发布系统的设置,
我们可以让我们已经启动的activity拥有更高的优先级来依据我们在代码中定义的标准来过滤和处理intent,而不是让别的声明了intent filter的activity来干扰
,甚至连自己声明在androidManifest中的intent filter都不会来干扰。也就是说foreground Dispatch的优先级大于intent filter。

第一种情况:当你的activity没有启动的时候,去扫描tag,那么系统中所有的intent filter都将一起参与过滤。

第二种情况:当你的actiity启动了,去扫描tag时,那么将直接使用你在foreground dispatch中代码写入的过滤标准。
如果这个标准没有命中任何intent,那么系统将使用所有activity声明的intent filter xml来过滤。

在OnCreate中你可以添加如下代码        

// Create a generic PendingIntent that will be deliver to this activity.
 The NFC stack will fill in the intent with the details of the discovered tag before delivering to this activity.

   mPendingIntent = PendingIntent.getActivity(this, 0,

             new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

        

        // 做一个IntentFilter过滤你想要的action 这里过滤的是ndef

        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

     //生成intentFilter   

        mFilters = new IntentFilter[] {

                ndef

        };

     

        // 做一个tech-list。可以看到是二维数据,每一个一维数组之间的关系是或,但是一个一维数组之内的各个项就是与的关系了

mTechLists =newString[][]{    newString[]{android.nfc.tech.IsoDep.class.getName()},    newString[]{android.nfc.tech.NfcV.class.getName()},    newString[]{android.nfc.tech.NfcF.class.getName()},    newString[]{android.nfc.tech.NfcA.class.getName()},    newString[]{android.nfc.tech.NfcB.class.getName()},    newString[]{android.nfc.tech.NfcBarcode.class.getName()},    newString[]{android.nfc.tech.MifareClassic.class.getName()},    newString[]{android.nfc.tech.MifareUltralight.class.getName()},    };

在onPause和 onResume中需要加入相应的代码。

public void onPause() {

 super.onPause();

取消注册 mAdapter.disableForegroundDispatch(this);

}

 

 public void onResume() {

 super.onResume();

//设定intentfilter和tech-list。如果两个都为null就代表优先接收任何形式的TAG action。也就是说系统会主动发TAG intent。

mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

}

0 0
原创粉丝点击