2014-11-03 212 views
0

创建ACTION_NDEF_DISCOVERED意图对于我正在写的应用程序,我想知道是否可以从代码创建ACTION_NDEF_DISCOVERED意图。通常,这个意图是由系统在读取ndef格式标签时创建的。它包含Tag类型的parcableextra。有没有办法从代码

意图的创建可能很简单,但是您是否也可以从代码创建标记或者是否按照我的设想不支持该类。

目标是向系统广播带有ndef记录的虚拟标记,然后可由调用ACTION_NDEF_DISCOVERED意图的应用程序处理该标记。

回答

1

您可以使用反射来获取模拟标记对象实例。像这样的东西应该工作:

NdefMessage ndefMsg = ...; 

Class tagClass = Tag.class; 
Method createMockTagMethod = tagClass.getMethod("createMockTag", byte[].class, int[].class, Bundle[].class); 

final int TECH_NFC_A = 1; 
final int TECH_NDEF = 6; 

final String EXTRA_NDEF_MSG = "ndefmsg"; 
final String EXTRA_NDEF_MAXLENGTH = "ndefmaxlength"; 
final String EXTRA_NDEF_CARDSTATE = "ndefcardstate"; 
final String EXTRA_NDEF_TYPE = "ndeftype"; 

Bundle ndefBundle = new Bundle(); 
ndefBundle.putInt(EXTRA_NDEF_MSG, 48); // result for getMaxSize() 
ndefBundle.putInt(EXTRA_NDEF_CARDSTATE, 1); // 1: read-only, 2: read/write 
ndefBundle.putInt(EXTRA_NDEF_TYPE, 2); // 1: T1T, 2: T2T, 3: T3T, 4: T4T, 101: MF Classic, 102: ICODE 
ndefBundle.putParcelable(EXTRA_NDEF_MSG, ndefMsg); 

Tag mockTag = (Tag)createMockTagMethod.invoke(null, 
     new byte[] { (byte)0x12, (byte)0x34, (byte)0x56, (byte)0x78 }, 
     new int[] { TECH_NFC_A, TECH_NDEF }, 
     new Bundle[] { null, ndefBundle }); 

这个问题是,你将无法连接到这个标签。因此,需要IO操作的Ndef对象(可以从模拟Tag实例中获得)的所有方法都带有实际标记或在NFC服务中注册的实际标记将会失败。具体而言,只有

  • getCachedNdefMessage()
  • getMaxSize()
  • getType()
  • isWritable()
  • getTag()

会工作。

如果您没有通过Tag对象作为NDEF_DISCOVERED意图的一部分,而只是使用EXTRA_NDEF_MESSAGES intent extra,那么几乎相同的功能可用。

相关问题