要解决的问题: 前台正在运行一个某个界面的Activity,这是有一个Tag靠近手机,要求处于前台的该Activity优先响应,获得该Tag的信息,并进行相应的后续操作。
实现步骤:
1.在变量声明的位置添加如下语句:
//----------NFC前台发布系统相关配置------------------
NfcAdapter mAdapter ;
PendingIntent pendingIntent;
IntentFilter[] intentFiltersArray;
String[][] techListsArray;
//---------------------------------------------
2.在onCreate方法下添加如下代码:
//---------NFC前台发布系统相关配置代码--------------------------------
mAdapter = NfcAdapter.getDefaultAdapter(ReadTrainInfo.this);
pendingIntent = PendingIntent . getActivity (
this , 0 , new Intent ( this , getClass ()). addFlags ( Intent . FLAG_ACTIVITY_SINGLE_TOP ), 0 );
IntentFilter ndef = new IntentFilter ( NfcAdapter . ACTION_NDEF_DISCOVERED );
try {
ndef . addDataType ( "text/plain" ); /* Handles all MIME based dispatches.
You should specify only the ones that you need. */
}
catch ( MalformedMimeTypeException e ) {
throw new RuntimeException ( "fail" , e );
}
//设置intent
intentFiltersArray = new IntentFilter [] {
ndef ,
};
//获得支持处理的technology类
techListsArray = new String [][] {
new String [] { NfcA . class . getName (),Ndef . class . getName (),NdefFormatable . class . getName (),MifareUltralight . class . getName () },
new String []{NfcA . class . getName (),Ndef . class . getName (),MifareUltralight . class . getName ()}
};
}
//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
//获得支持处理的technology类
techListsArray = new String [][] {
new String [] { NfcA . class . getName (),Ndef . class . getName (),NdefFormatable . class . getName (),MifareUltralight . class . getName () },
new String []{NfcA . class . getName (),Ndef . class . getName (),MifareUltralight . class . getName ()}
new String [] { NfcA . class . getName (),Ndef . class . getName (),NdefFormatable . class . getName (),MifareUltralight . class . getName () 为过滤的Tag卡的类型
每个数组可以匹配一个特定类型的Tag,当有匹配以上技术的tag出现时,该Activity就会优先处理。
然后添加如下方法:
public void onPause () {
super . onPause ();
mAdapter.disableForegroundDispatch(this); //不在前台时关闭前台发布系统
Log.i("onPause", "aaaaaaaaaaaaaaaaaaaaaaa");
}
public void onResume () {
super . onResume ();
mAdapter . enableForegroundDispatch ( this , pendingIntent , intentFiltersArray , techListsArray ); //恢复时开启前台发布系统
Log.i("onResume", "aaaaaaaaaaaaaaaaaaaaaaa");
}
public void onNewIntent ( Intent intent ) {
//读取CardId信息
NfcUtil.readFromTagContent(intent);
parseInfoFromTag();
//根据cardid读取培训相关的信息
Toast.makeText(getApplication(), "写入成功", Toast.LENGTH_SHORT).show();
Log.i("onNewIntent", "aaaaaaaaaaaaaaaaaaaaaaa");
APITestTask downFromTrain = new APITestTask();
downFromTrain.execute(cardid);
}
onNewIntent :当有匹配的Tag靠近时,该方法被触发,intent包含了Tag 中的所有信息,可以通过传过来的该intent实现各种对Tag的操作。